我真的不确定我是否以正确的方式这样做!
我有一个正在测试的模块和一个测试脚本。MUT 中有 2 个函数,其中一个函数使用另一个函数。我尝试模拟该模块以用模拟替换实际的支持功能,但它似乎没有被调用。我这样做是正确的还是你不能因为引用平等而这样做?
穆特
const total_users = 100;
export function getRandomIntInclusive(min=0, max=0) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
}
export default function getUsername(name='user'){
return `${name}_${getRandomIntInclusive(1, total_users)}`;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
import getUsername, {getRandomIntInclusive} from "../generateUsername";
const randomSpy = jest.spyOn(Math, 'random');
jest.mock('../generateUsername', () => {
const originalModule = jest.requireActual('../generateUsername');
return {
__esModule: true,
...originalModule,
getRandomIntInclusive: jest.fn((min=0, max=0) => 5), // <-- mock
};
});
describe("The 'randomNumber' function", () => {
beforeEach(() => {
randomSpy.mockClear();
});
it("Generates a random number between 2 values (inclusive)", () => {
randomSpy.mockReturnValue(0.9);
expect(getUsername('john')).toBe(`john_91`);
expect(randomSpy).toBeCalledTimes(1);
expect(getRandomIntInclusive).toHaveBeenCalled(); // <-- execution of mock. Test fails here
});
it.todo('Throws an error if no name is passed')
});
Run Code Online (Sandbox Code Playgroud)
Result:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5190 次 |
| 最近记录: |