【问题标题】:Error: done() invoked with non-Error: {"req":{ ......} request done without error, but test didn't pass错误:用非错误调用完成():{“req”:{......}请求完成没有错误,但测试没有通过
【发布时间】:2018-04-08 12:24:41
【问题描述】:

我正在尝试解决我的测试,但似乎没有任何效果。目前我正在使用 mocha、supertest 和 chai,但是即使请求成功执行,我也看到了这个我无法摆脱的恼人错误:

done() 以非错误调用:{“req”:{ …} 请求完成且没有错误,但测试未通过

代码:

let should = require('chai').should(),
    expect = require('chai').expect,
    constants = require('./constants'),
    supertest = require('supertest'),
    api = supertest(constants.ENVIRONMENT),
    express = require('express'),
    http = require('http'),
    request = require('request'),
    app = express(),
    bodyParser = require('body-parser'),
    port = process.env.PORT || 3000,
    assert = require('assert');
    
    describe('Create device API call', () => {

    function createToken() {
        return new Promise(resolve =>
            request.post(
                'myURl',
                { 
                 json: 
                        { 
                          "username": "myUsername", 
                          "password": "myPassword" 
                        } 
                },
                function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        let token = (body.accessList[0].accessToken);
                        resolve(token);

                    }
                    else {
                        console.log("Server error get token")
                    }

                })
        )
    }

    it('should create device', async (done) => {

        let token = await createToken();

        //console.log(`Token is ${token}`);

        api.post('/deviceManifests/1/devices')
            .set('Accept', 'application/json')
            .set('Authorization', `Bearer ${token}`)
            .send({
                "name": "QA integration",
                "deviceKey": "somekey38957",
                "defaultBinding": true
            })
            .expect('content-Type', /json/)
            .expect(201)
            .expect(function (res, err) {
                assert.equal(res.body.name, 'QA integration');

            }).then(done);
    });

});    

【问题讨论】:

  • 除了更改 then 以包含函数或箭头键 func 之外,在 .then 之后添加一个 catch 块用于未解决的 Promise 拒绝。不要假设没有一个承诺拒绝场景的捕获就没有错误。
  • 非常感谢,同时我按照你说的解决了:)

标签: node.js testing mocha.js chai supertest


【解决方案1】:

您将 done 传递给 then

因此,done 将被传递一个参数。

但是,如果您将参数传递给 done,它会认为这是一个错误。

试试这个:

.then(function () {
  done()
})

...或使用箭头函数:

.then(() => done())

【讨论】:

  • > 它期望它是一个错误 是的,但是 是什么 是一个错误?无论我将什么传递给done(),我都会保持done() invoked with non-Error
  • @yPhil 这个done 回调接受Error 的实例或假值。此处的文档:mochajs.org/#asynchronous-code
  • 谢谢!现在我只需要找出这两个东西到底是什么(错误实例(或其子类)或虚假值)注意文档没有提供任何定义或链接:(我的应用程序抛出了传递的错误到done(),所以我需要知道什么是可接受的错误确切地是;可能是一个列表。但是好的,我会尝试false
  • @yPhil 没问题 :)
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
相关资源
最近更新 更多