【发布时间】:2019-03-15 20:31:02
【问题描述】:
我正在尝试使用返回 JSON 的方法来模拟一个实用程序库类。
实际的库结构
module.exports = class Common() {
getConfig() {
return {
real: 'data'
}
}
被测文件如下:
const Common = require('./common');
const common = new Common();
const config = common.getConfig();
...
const someFunction = function() {
// config.real is used inside this function
}
我正在尝试模拟 Common 类并为每个 Jest 测试返回不同的配置 JSON。
const fileUnderTest = require('./../fileUnderTest.js');
const Common = require('./../common.js');
jest.mock('./../common.js');
describe('something', () => {
it('test one', () => {
Common.getConfig = jest.fn().mockImplementation(() => {
return {
real : 'fake' // This should be returned for test one
};
});
fileUnderTest.someFunction(); //config.real is undefined at this point
});
it('test two', () => {
Common.getConfig = jest.fn().mockImplementation(() => {
return {
real : 'fake2' // This should be returned for test two
};
});
})
})
是否可以从测试文件顶部common.js的自动模拟创建的模拟类方法中设置返回值?
我尝试过使用mockReturnValueOnce() 等。
【问题讨论】:
标签: javascript unit-testing mocking jestjs