模块-a.js
class Math {
pi() {
return 3.14;
}
}
export default Math
模块-b.js
import Math from './module-a';
const piVal = Math.pi();
export const doSomeCalc = (a) => {
return piVal + a;
}
模块-b.test.js
describe('module b', () => {
it('should return correct value', () => {
// I want to mock the return value of pi() here
return import('./module-b').then(module => {
expect(
module.doSomeCalc(20)
).toBe(23.14);
});
});
})
我如何在这里嘲笑
Math.pi()
?
我需要动态导入模块,因为一旦导入模块就会评估
Math.pi()
。
首先,如果你调用
Math.pi()
方法,它应该是类的静态方法。
jest.doMock(moduleName, factory, options)
来模拟 module-a.js
模块
例如
module-a.js
:
class Math {
static pi() {
return 3.14;
}
}
export default Math;
module-b.js
:
import Math from './module-a';
const piVal = Math.pi();
export const doSomeCalc = (a) => {
return piVal + a;
};
module-b.test.js
:
describe('module b', () => {
beforeEach(() => {
jest.resetModules();
});
it('should return correct value 1', () => {
class MockMath {
static pi() {
return 1;
}
}
jest.doMock('./module-a.js', () => {
return {
default: MockMath,
__esModule: true,
};
});
return import('./module-b').then((module) => {
expect(module.doSomeCalc(20)).toBe(21);
});
});
it('should return correct value 2', () => {
class MockMath {
static pi() {
return 2;
}
}
jest.doMock('./module-a.js', () => {
return {
default: MockMath,
__esModule: true,
};
});
return import('./module-b').then((module) => {
expect(module.doSomeCalc(20)).toBe(22);
});
});
});
测试结果:
PASS stackoverflow/79002536/module-b.test.js
module b
√ should return correct value 1 (4 ms)
√ should return correct value 2 (1 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.756 s, estimated 1 s
Ran all test suites related to changed files.