【问题标题】:Test with Promise not entering then/catch使用 Promise 进行测试,不输入 then/catch
【发布时间】:2020-04-18 18:42:55
【问题描述】:

我有以下测试

describe('User - Sign up', function() {
 it('should not register a new user because of missing data on form', function (done) {
    const email = "testemail@gmail.com";
    const req = { body: { email: email }};

    const signUp = controller.signUp(req);

    console.log(signUp);
    signUp
        .then(data => {
            console.log('ok');
        })
        .catch(err => {
            console.log('error')
        });

    done();
});

注册功能如下:

return new Promise(((resolve, reject) => {
    validator.checkAsync(async () => {
        const user = {
            email: req.body.email,
            password: await pwdHash.hashPassword(req.body.password)
        }

        await store.signUp(user);

        resolve({
            valid: true
        });
    }, () => {
        reject(validator.errors);
    });
}));

但是,测试没有返回任何控制台日志并且它正在通过。 我错过了什么?

更新:

我可以使用以下代码修复它:

    it('should not register a new user when missing data on form', async function () {
    const email = "testemail@gmail.com";

    const res = await chai.request('http://localhost:3000')
        .post('/user/signup',)
        .send({ email: email });

    expect(res).to.have.status(401);
});

基于 cmets 和此评论: https://stackoverflow.com/a/46217308/868699

【问题讨论】:

    标签: node.js unit-testing express testing


    【解决方案1】:

    您在Promise 完成之前调用done。

    signUp
            .then(data => done())
            .catch(done);
    

    如果进入.catch,done会被调用error,测试失败。如果传递给done 的参数是真实的,它将无法通过测试(至少对于mocha)。

    你也可以使用async/await语法,去掉done

     it('should not register a new...', async function() {
        /* ... */
        await controller.signUp(req)
     });
    
    

    【讨论】:

    • 我将其更改为const signUp = controller.signUp(req); console.log(signUp); signUp .then(data => { console.log('ok'); done(); }) .catch(err => { console.log('error') done(); }); ,但它记录了 Promise { } 并引发错误说 Error: Timeout of 2000ms exceeded。对于异步测试和钩子,确保调用“done()”
    • 因为它比2000ms花费更多的时间,所以增加超时时间。
    • 你还有这个问题吗?
    • 是的,我将超时时间增加到11000ms 没有运气......我被卡住了
    • 显示更新后的代码。并尝试使用async/await
    猜你喜欢
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多