开玩笑地测试一个承诺包装的请求

时间:2018-08-08 00:34:48

标签: javascript node.js promise jestjs

我有一个request调用,包装在一个Promise链中,如下所示:

  import * as request from 'request';

  public async getData (): Promise<string> {
    const token = await this.util.getToken();
    const options = {
      withCredentials: true,
      Connection: 'keep-alive'
    };
    return new Promise<string>((resolve, reject) => {
      request(this._Host, options, (err, data) => {
        if (err != null) {
          return reject('Fetch Failed');
        }
        const values = JSON.parse(data.body);
        this._result = values.result;
        return resolve('Fetch Success');
      });
    });
  }

我正在使用jest通过以下代码测试此方法

it('should fetch data', async(done) => {
  const classobj = new ClassName(config);
  (classobj as any).util.getToken.// tslint:disable-line
   mockResolvedValue('some-token');
  const spy = jest.mock('request', (path, options) => {
    return Promise.resolve('Fetch Success');
  });
  const dispatcher = await classobj.getData().then(done());
});

但是request块中的代码永远不会被触发。但是测试也显示运行成功。我还注意到,如果我传递return new Promise中已经解析的值,那么代码块将被触发而没有任何问题。这段代码中缺少测试request调用的内容吗?

0 个答案:

没有答案