我正在尝试检查同一文件中两个功能的实现。 其中一个函数将调用另一个函数,我想检查它是否确实发生。
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);
});
});
但是我得到这个错误:
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)
答案 0 :(得分:0)
通过更改strings.js中的导出函数来导出其中包含每个函数的类,从而解决了该问题。然后在测试中,我启动了该类的新实例,并将其用于测试。