[英]How to use jest to mock the results being sent back in the callback functions
有沒有辦法模擬storage
對象,以便我可以在執行storage.get
時控制回調函數中傳回的err
和v
?
const mod = (() => {
let value;
return {
init: (storage) => {
storage.get('key', (err, v) => {
value = v;
});
},
get: () => value
};
})();
由於我關心storage.get
副作用,我不能簡單地執行mockImplementation
來覆蓋該函數。 那是對的嗎?
創建一個mod.init
storage
對象並將其傳遞給mod.init
方法。
例如
index.ts
:
const mod = (() => {
let value;
return {
init: (storage) => {
storage.get('key', (err, v) => {
value = v;
});
},
get: () => value,
};
})();
export { mod };
index.test.ts
:
import { mod } from './';
describe('63640360', () => {
it('should pass', () => {
const mStorage = {
get: jest.fn().mockImplementationOnce((key, callback) => {
callback(null, 'teresa teng');
}),
};
mod.init(mStorage);
const actual = mod.get();
expect(actual).toBe('teresa teng');
expect(mStorage.get).toBeCalledWith('key', expect.any(Function));
});
});
帶有覆蓋率報告的單元測試結果:
PASS src/stackoverflow/63640360/index.test.ts
63640360
✓ should pass (5ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.079s, estimated 9s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.