简体   繁体   中英

jest mocking module functions

I am trying to make assertions on jest mocked functions and my code is like this

const saveProductMock = jest.fn((product) => {
  //someLogic
  return
});

jest.mock('./db', () => {
  return {
    saveProduct: saveProductMock
  }
})

my assertion should be like

expect(saveProductMock.mock.calls[0][0]).toBe(product)

but I got the following error:

ReferenceError: Cannot access 'saveProductMock' before initializing at the line saveProduct: saveProductMock

jest.mock() is hoisted . As a result, the code is actually ran like:

jest.mock('./db', () => {
  return {
    saveProduct: saveProductMock
  }
})

const saveProductMock = jest.fn((product) => {
  //someLogic
  return
});

//WAS HERE

Solution would be to put the login inside jest.mock(); .

jest.mock('./db', () => {
    return {
        saveProduct: jest.fn((product) => {
            //someLogic
            return
        })
    }
})

Other solution is to simply mock the entire module then, define explicit return value to use.

const db = require('./db');
jest.mock('./db');

it("example", () => {
    db.saveProduct.mockReturnValue(123);
    /** different types of return methods */
    // db.saveProduct.mockResolvedValue(123);

    const product = db.saveProduct();
    const expectedProduct = "xyz";
    expect(product).toBe(expectedProduct)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM