2
votes

I want to test the return value of a mock function in jest.

In following code i want to mock fs module's mkdirSync function

const fs = require("fs");


describe("Testing mock fs.mkdirSync", () => {
    fs.mkdirSync = jest.fn().mockReturnValue(5);
    fs.mkdirSync("./apple");

    it("fs.mkdirSync must have been called", () => {
        expect(fs.mkdirSync).toHaveBeenCalled();
    });

    //This test fails with TypeError: Cannot read property '0' of undefined

    it("fs.mkdirSync last return value must be 5", () => {
        expect(fs.mkdirSync.mock.results[0].value).toBe(5);
    });



});

Second test fails with TypeError: Cannot read property '0' of undefined

2
In your example, you're doing exactly as the documentation for jest suggest. I copy-pasted your code and both tests passed in jest. There's something you've omitted that's making the test fail, because your code is fine.Jemi Salo
i have installed jest globally, and my jest version is v20.04 and i am running the test with jest --watchmanas
may i know which version jest you are using and how are you running the testmanas
I've jest version 23.4.0. I'm running an npm script "scripts": { ... "test": "jest" }. The code is in a .test.js file. all in a project created with create-react-app.Jemi Salo
but my create-react-app installs the jest version 20.0.4 how did you get the latest version of jest in create-react-app without ejecting it ???manas

2 Answers

4
votes

Why would you want to test the return value of a jest mocked function? At this point you are testing jest.

You could assign fs.mkdirSync to a variable and test that value since that is the returned value:

const result = fs.mkdirSync("./apple");
it("fs.mkdirSync last return value must be 5", () => {
    expect(result).toBe(5);
});
0
votes

Your code is correct, but your jest installation is an outdated version.

Copy-pasting your tests into a fresh create-react-app boilerplate and running jest will result in the behaviour described in the question.

run npm install jest --save-dev to install the latest version of jest.

Running jest now should result in both tests passing.