Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking stdout/stderr with jest #368

Closed
faustbrian opened this issue Sep 6, 2019 · 2 comments

Comments

@faustbrian
Copy link

commented Sep 6, 2019

I am currently writing tests for some parts that decide how to proceed based on stdout, stderr and exitCode but I seem to be unable to mock them through jest.

import execa from "execa";

const spy = jest.spyOn(execa, "sync").mockReturnValue({
    command: "whoami",
    exitCode: 0,
    exitCodeName: "SUCCESS",
    stdout: "stdout",
    stderr: "stderr",
    failed: false,
    timedOut: false,
    isCanceled: false,
    killed: false,
});

someFunctionThatCallsExecaSync();

expect(spy).toHaveBeenCalled();

This way of doing it works if I apply it to child_process and a few other packages that can execute commands but with execa it doesn't seem to have any affect as the execa.sync call in someFunctionThatCallsExecaSync is executed and returns its real outcome.

What would be the right way of mocking the values of stdout, stderr and exitCode if it isn't possible through a spy? Any suggestions on how to properly mock those values are appreciated.

@ehmicky

This comment has been minimized.

Copy link
Collaborator

commented Sep 6, 2019

There should not be anything specific to execa there.

For example, if you were to wrap execa.sync() in an function:

const execaSync = function(...args) {
  return execa.sync(...args)
}

Then spy on this, and it does not work, then it means there is something wrong with your jest/mocking setup, not with execa. In that case, you should ask on the jest repository.

Really, execa.sync() is just a regular function, we don't do anything specific there.

@faustbrian

This comment has been minimized.

Copy link
Author

commented Sep 6, 2019

Alright, will try my luck there. Just seemed odd that the mock works for other packages and child_process. Thanks!

@faustbrian faustbrian closed this Sep 6, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.