[英]Mock function call only once
我正在嘗試檢查同一文件中兩個功能的實現。 其中一個函數將調用另一個函數,我想檢查它是否確實發生。
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)
通過更改strings.js中導出的函數以導出其中包含每個函數的類來解決該問題。 然后在測試中,我啟動了該類的新實例,並將其用於測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.