【问题标题】: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 };

【问题讨论】:

  • 如果您正在构建response 的模拟,它的json 方法需要返回一个promise,因为这是真实对象返回的。或查看docs.angularjs.org/api/ngMock/service/…
  • 它工作正常,非常感谢

标签: 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2020-06-24
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多