在then()中的Jest模拟私有方法

时间:2018-02-21 22:48:46

标签: javascript angularjs jest

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 };

1 个答案:

答案 0 :(得分:0)

response.json方法应返回一个promise。例如

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