【问题标题】:Jest mock private method in then()then() 中的笑话模拟私有方法
【发布时间】:2020-07-28 17:16:06
【问题描述】:
export const get = () => {
return fetch().then((response) => funcA(response));
};
const funcA = (response) => {
if (!response.ok) {
return response.json().then((data) => {
throw Error(...);
});
}
};
我如何模拟 response.json().then() ?我收到错误response.json(...).then is not a function。
我将 json() 放在我嘲笑的响应中
response = { ok: false, json: () => err };
【问题讨论】:
标签:
javascript
angularjs
jestjs
【解决方案1】:
response.json 方法应该返回一个承诺。例如
index.ts:
export const funcA = (response) => {
if (!response.ok) {
return response.json().then((data) => {
throw Error(data);
});
}
};
index.test.ts:
import { funcA } from './';
describe('48916842', () => {
it('should pass', () => {
const mResponse = { ok: false, json: jest.fn().mockRejectedValueOnce('custom error') };
expect(funcA(mResponse)).rejects.toThrowError('custom error');
});
});
带有覆盖率报告的单元测试结果:
PASS stackoverflow/48916842/index.test.ts (10.276s)
48916842
✓ should pass (5ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 75 | 50 | 50 | 75 |
index.ts | 75 | 50 | 50 | 75 | 4
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.929s, estimated 12s