[英]How to use jest to mock the results being sent back in the callback functions
Is there a way to mock the storage
object so I can control the err
and v
passed back in the callback function when I do storage.get
?有没有办法模拟storage
对象,以便我可以在执行storage.get
时控制回调函数中传回的err
和v
?
const mod = (() => {
let value;
return {
init: (storage) => {
storage.get('key', (err, v) => {
value = v;
});
},
get: () => value
};
})();
Since I care about the side effects of storage.get
I cannot simply do mockImplementation
to override the function.由于我关心storage.get
副作用,我不能简单地执行mockImplementation
来覆盖该函数。 is that correct?那是对的吗?
Create a mocked storage
object and pass it into mod.init
method.创建一个mod.init
storage
对象并将其传递给mod.init
方法。
Eg例如
index.ts
: index.ts
:
const mod = (() => {
let value;
return {
init: (storage) => {
storage.get('key', (err, v) => {
value = v;
});
},
get: () => value,
};
})();
export { mod };
index.test.ts
: 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));
});
});
unit test result with coverage report:带有覆盖率报告的单元测试结果:
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.