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

Throw tslint warning when use mockResolvedValueOnce and async/await

我模拟了 request-promise 模块,一切正常,除了 tslint 发出警告。

这是我的单元测试:

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)

似乎 request.get('1')request.get 上执行 mockResolvedValueOnce 后未被视为承诺。

更新

如果我删除 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

我使用类型转换来解决这个问题。因为我确定 request.get('1') 在执行 mockResolvedValueOnce 之后是 Promise

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