[英]Mock function call only once
I am trying to check the implementation of two functions within the same file. 我正在尝试检查同一文件中两个功能的实现。 One of the functions will call the other function and I want to check that it actually happens. 其中一个函数将调用另一个函数,我想检查它是否确实发生。
import * as strings from './strings';
const generateUuidSpy = jest.spyOn(strings, 'generateUuid');
describe('getContextId()', () => {
it('it should return a string id if given context and number', () => {
const actual = strings.getContextId('testQueue', 5);
const expected = 's1-s5';
expect(typeof actual).toBe('string');
expect(actual).toEqual(expected);
});
it('it should execute generateUuid()', () => {
strings.getContextId('notTestQueue');
expect(generateUuidSpy).toHaveBeenCalled();
});
});
describe('generateUuid()', () => {
it('it should return a 36 char UUID string', () => {
generateUuidSpy.mockRestore();
const actual = strings.generateUuid();
const expected = /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/;
expect(actual.length).toBe(36);
expect(typeof actual).toBe('string');
expect(expected.test(actual)).toBe(true);
});
});
But I get this error: 但是我得到这个错误:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called, but it was not called.
12 | it('it should execute generateUuid()', () => {
13 | strings.getContextId('notTestQueue');
> 14 | expect(generateUuidSpy).toHaveBeenCalled();
| ^
15 | });
16 | });
17 |
at Object.toHaveBeenCalled (src/helpers/strings.test.js:14:29)
Solved the issue by changing the exported functions inside strings.js to export a class with each function inside it. 通过更改strings.js中导出的函数以导出其中包含每个函数的类来解决该问题。 Then in my test I initiated a new instance of the class and used that for the tests. 然后在测试中,我启动了该类的新实例,并将其用于测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.