【发布时间】:2021-04-15 19:52:08
【问题描述】:
我一直在尝试模拟一个在另一个文件中导入并在类中使用的函数。这里有类似的问题,我经历了很多,但仍然无法让我的测试正常工作。这是我的代码结构:
//util.js
export const stageHelper = (key) => {
return STAGE_NAMES[key];
};
//main.js
import {stageHelper} from './util'
class Main {
static config = {
value: stageHelper('abc'),
}
static getValue() {
return this.config.value;
}
}
//main.spec.js
import * as util from './util';
import {Configuration} from '../configuration/configuration';
jest.mock('./util');
describe('Main', () => {
const utilSpy = jest.spyOn(util, 'stageHelper').mockImplementation(() => 'testValue');
//util.stageHelper = jest.fn().mockImplementation(() => 'testValue'); // tried this too
//utilSpy.mockReturnValue('ja'); // tried this too
expect(Main.getValue()).toEqual('testValue'); // this test fails - the value is 'undefined'
});
从我的测试中调用Main.getValue() 时,我得到undefined。但是,我希望这会返回 testValue,因为这就是我模拟的返回值。
有人可以帮我解决这个问题吗?这将不胜感激!
【问题讨论】:
-
(在导入
Configuration之前,您是否尝试过模拟./util?我不确定这是否重要。) -
是的,这就是我所做的
标签: javascript reactjs testing jestjs mocking