简体   繁体   English

使用mockResolvedValueOnce和async / await时抛出tslint警告

[英]Throw tslint warning when use mockResolvedValueOnce and async/await

I mocked request-promise module, everything is fine except tslint complains a warning. 我嘲笑了request-promise模块,除了tslint抱怨警告之外,一切都很好。

Here is my unit test: 这是我的单元测试:

import * as request from 'request-promise';

jest.mock('request-promise', () => {
  return {
    __esModule: true,
    get: jest.fn(),
  };
});

describe('csv.service.ts', () => {
  it('should mock request-promise module correctly', () => {
    expect(jest.isMockFunction(request.get)).toBeTruthy();
  });
  it('should mock get method correctly', async () => {
    (request.get as jest.Mock).mockResolvedValueOnce('go?');
    const actualValue = await request.get('1');
    expect(actualValue).toBe('go?');
  });
});

Refactor this redundant 'await' on a non-promise. 在无承诺的情况下重构此冗余的“等待”。 (no-invalid-await)tslint(1) (无无效等待)tslint(1)

It seems that request.get('1') is not treat as a promise after executing mockResolvedValueOnce on request.get . 似乎request.get('1')不当作执行后承诺mockResolvedValueOncerequest.get

update 更新

If I remove async/await , the second unit test will failed. 如果删除async/await ,则第二个单元测试将失败。

 FAIL  src/tests/services/core/csv.service.spec.ts
  csv.service.ts
    ✓ should mock request-promise module correctly (5ms)
    ✕ should mock get method correctly (9ms)

  ● csv.service.ts › should mock get method correctly

    expect(received).toBe(expected) // Object.is equality

    Expected: "go?"
    Received: {}

    Difference:

      Comparing two different types of values. Expected string but received object.

      17 | 
      18 |     const actualValue = request.get('1');
    > 19 |     expect(actualValue).toBe('go?');
         |                         ^
      20 |   });
      21 | });
      22 | 

      at Object.it (src/tests/services/core/csv.service.spec.ts:19:25)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.203s, estimated 2s

I use typecast to solve this issue. 我使用类型转换解决此问题。 Because I am sure request.get('1') is a Promise after executing mockResolvedValueOnce on it. 因为我确定request.get('1')在对它执行了mockResolvedValueOnce之后是一个Promise

const actualValue = await (request.get('1') as PromiseLike<string>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM