无法使用 done() 或 async/await 来修复我的承诺未解决

问题描述

我正在尝试使用 chai-http 和 mocha 学习 api 测试。 我已经尝试过 done()async/await,但我不明白为什么它没有解决以下问题 -

错误 -

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

规格文件 -

import * as chai from 'chai';
import { assert } from 'chai';
import chaiHttp = require('chai-http');
import 'mocha';

chai.use(chaiHttp);
const expect = chai.expect;
const url = 'https://api.weather.gov';

describe('Weather API',() => {

    it('Should be up and running',() => {
        return chai.request(url).get('/').then(res => {
            expect(res).to.be.status(200);
        });
    });

    it('Should return weather of washington monument',() => {
        return chai.request(url).get('/gridpoints/LWX/96,70/forecast')
            .set('User-Agent','test@email.com')
            .set('Accept','application/vnd.noaa.dwml+xml')
            .then(res => {
                expect(res).to.be.status(200);
                console.log(res.body.properties.periods);
            });
    });
});

否则,我没有正确实施我尝试过的解决方案。非常感谢任何帮助。

解决方法

当你使用 Promise 时,你必须使用 chai-as-promised,有了这个,你可以这样使用 async/await:

import chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);

//...

it('Should be up and running',async () => {
    var response = await chai.request(url).get('/')
    return response.should.have.status(200)
    // you can use "return expect(response).to.have.status(200);" too
  })

请注意,现在不使用 done,而是添加了 return

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...