我正在使用Typescript,使用Mocha并尝试使用ES6 async/await生成器。使用Typescript异步的摩卡API测试
这里是我的代码:
"use strict";
import * as console from 'console';
import { Config } from './Config';
import * as assert from 'assert';
import * as mocha from 'mocha';
import fetch from 'node-fetch';
async function createExchangeRate(date: string) {
let body = JSON.stringify({
'ts': date,
'gbptoUSD': 1.0,
'eurtoUSD': 1.0,
'cyntoUSD': 1.0
});
return fetch(`${Config.host()}/exchangeRate`, { method: 'POST', body: body });
}
describe('/exchangeRate', function() {
let date = '2016-01-01';
it('creates the exchange rate', async function(done) {
let response = await createExchangeRate(date);
console.log('Got my promise!');
let body = await response.json();
assert.equal(response.status, 204);
assert.ok(body.uuid);
done();
});
});
一切正确编译但通过createExchangeRate
返回的承诺似乎从来没有得到解决,并且永远不会达到console.log
。
最终摩卡测试时间了,我得到类似的消息:
Error: timeout of 5000ms exceeded. Ensure the done() callback is being called in this test.
我已经尝试了各种不同的格式,但不能看到我要去哪里错了...
UPDATE
如果我修改我的测试,以除去异步/等待关键字,它的工作原理:
it('creates the exchange rate',() => {
createExchangeRate(date).then(function(response) {
expect(response.status).to.equal(204);
response.json().then(function(body) {
expect(body.uuid).to.be.ok;
});
});
});
你是否试过在Mocha之外将测试代码作为普通函数运行? *如果*您可以在没有摩卡的情况下复制相同的行为,那非常有用。首先,您可以将注意力集中在问题实际存在的位置(而不是Mocha)。其次,你可以在这里重写你的问题,以消除摩卡,这将有助于让更多读者阅读你的问题。人们倾向于跳过标有他们不知道的技术的问题。问题标签越多,潜在读者的集合越小。 – Louis
您的函数createExchangeRate可能比默认超时多吗?请记住,超时也包含初始化代码(因此它不仅仅是您的代码执行)。首先,你可以在'await'代码前加'this.timeout = someValue'来尝试增加超时。 – SzybkiSasza
我试着添加30秒的超时,但不幸的是没有任何区别。 – timothyclifford