简体   繁体   English

开玩笑 mocking 模块功能

[英]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 ReferenceError:在行 saveProduct 初始化之前无法访问“saveProductMock” :saveProductMock

jest.mock() is hoisted . jest.mock()吊起 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(); . .

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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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