首页 文章

使用Mocha时,超时超时错误

提问于
浏览
3

在使用 Mocha 进行测试时,我在运行server.test.js时遇到以下错误

1)“每个”钩子之前“应该得到所有待办事项”:错误:超过2000毫秒超时 . 对于异步测试和挂钩,确保调用“done()”;如果返回Promise,请确保它已解决 .

server.test.js

const expect = require('expect');
const request =  require('supertest');

const {app} = require('./../server');
const {Todo} = require('./../todos');


const todos = [
{
    text: 'This is text 1'
},
{
    text: 'This is text 2'
}
];


beforeEach((done) => {

Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
}).then(() => done());
});


describe('GET /todos', () => {
it('should get all todos', (done) => {

    request(app)
        .get('/todos')
        .expect(200)
        .expect(res => {
            expect(res.body.length).toBe(2);
        })
        .end(done);
});
});

但是,如果我在 beforeEach() 方法中做了一些更改,例如:

更新了server.test.js

const expect = require('expect');
const request =  require('supertest');

const {app} = require('./../server');
const {Todo} = require('./../todos');


const todos = [
{
    text: 'This is text 1'
},
{
    text: 'This is text 2'
}
];

beforeEach((done) => {

Todo.remove({}).then(() => {
    Todo.insertMany(todos);
    done();
})
});


describe('GET /todos', () => {
it('should get all todos', (done) => {

    request(app)
        .get('/todos')
        .expect(200)
        .expect(
            expect(res.body.length).toBe(2);
        })
        .end(done);
});
});

然后我没有错误 . 基本上,通过链接 beforeEach() 方法中的promises我遇到了一个错误,但没有一切都很好 . 谁能解释为什么会这样?

server.js

var express = require('express');
var body_parser = require('body-parser');

const {mongoose} = require('./mongoose.js');
const {Todo} = require('./todos');
const {Todo_1} = require('./todos');

var app = express();

app.use(body_parser.json());



//  using GET method
app.get('/todos', (req, res) => {
Todo.find().then((todos) => {
    res.send(todos);
}, (err) => {
    res.status(400).send(err);
});
});

module.exports = {app}

app.listen(3000, () => {
console.log('Server is up on the port 3000');

})

2 回答

  • 1

    这是处理承诺的错误方法:

    Todo.remove({}).then(() => {
        Todo.insertMany(todos);
        done();
    })
    });
    

    Todo.insertMany 可能是异步的并返回一个promise,它与promise链分离 . 如果有错误,它们将导致未处理的拒绝承诺,并且由于测试依赖于插入的行,这将导致竞争条件:

    错误:超出2000ms的超时 . 对于异步测试和挂钩,确保调用“done()”;如果返回Promise,请确保它已解决 .

    意思是它所说的 . done 要么未被调用,要么超时 . 永远不会调用 done ,因为不处理错误 . 它应该是 .then(done, done) .

    由于Mocha支持承诺,一个正确的方法是:

    beforeEach(() => 
      Todo.remove({})
      .then(() => Todo.insertMany(todos))
    );
    

    应该返回在promise链中出现的每个承诺 .

  • 0

    而不是像这样将localhost放在url中:“mongodb:// localhost:27017 / yourDbName”

    使用127.0.0.1,所以它变成如下:

    “MongoDB的://127.0.0.1:27017 / yourDbName”

    我不知道这个解决方案背后的原因是什么,但似乎服务器需要一些时间来处理并找出localhost的IP是什么 .

    希望此解决方案能够解决您的问题 .

相关问题