【问题标题】:how to test promise returning functions如何测试承诺返回函数
【发布时间】:2018-07-27 05:30:24
【问题描述】:

我有以下返回 Promise 的异步函数。

static getAccessToken(env: DeploymentEnv, username: string, password: string): Promise<AccessToken>;

现在,这是我为它编写的单元测试。

it("should be able to get access token",async ()=>{
    let accessToken = await IModelHubServiceBusClient.getAccessToken('QA',
                      'abc@xyz.com',
                      'abc')!;

    assert.exists(accessToken);
});

运行时,测试失败,提示以下错误:

should be able to get access token:
 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我做错了什么,任何建议将不胜感激。 提前致谢。

【问题讨论】:

  • 向我们展示getAccessToken 的实现,或确保它始终被解析/拒绝
  • static getAccessToken(env, username, password) { return __awaiter(this, void 0, void 0, function* () { const promise = new Promise((resolve, reject) =&gt; __awaiter(this, void 0, void 0, function* () { let auth = yield new ImsClients_1.ImsActiveSecureTokenClient(env).getToken(username, password); let atoken = yield new ImsClients_1.ImsDelegationSecureTokenClient(env).getToken(auth); if (atoken) { resolve(atoken); } reject("Failed to get token"); })); return promise; }); }

标签: typescript asynchronous promise mocha.js chai


【解决方案1】:

如果你测试异步代码,你需要使用done回调

it("should be able to get access token",async (done)=>{
    let accessToken = await IModelHubServiceBusClient.getAccessToken('QA',
                      'bistroDEV_pmadm1@mailinator.com',
                      'pmadm1')!;

    assert.exists(accessToken);
    done();
});

【讨论】:

  • 我刚试过这个并返回同样的错误。还有什么建议吗?错误是:错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回 Promise,请确保它已解决。
  • 我尝试在其中添加一个控制台,如下所示:it("should be able to get access token",async (done)=&gt;{ let accessToken = await IModelHubServiceBusClient.getAccessToken('QA', 'bistroDEV_pmadm1@mailinator.com', 'pmadm1')!; console.log(accessToken); //assert.exists(accessToken); done(); }); 现在它仍然会抛出相同的异常,但几秒钟后,它也会输出 accessToken 的值。
  • 最近的 mocha 版本绝对不需要这个
猜你喜欢
  • 2017-04-07
  • 2015-03-30
  • 2016-10-04
  • 2017-05-26
  • 2016-12-18
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多