node.js - 尽管使用 done,Mocha 在 Before 钩子中调用异步承诺链超时
问题描述
我正在使用 node.js 上的 mocha 和 chai 将异步集成测试套件运行到猫鼬数据库中。大多数都运行良好,但对于一个我必须使用 before 钩子执行一些预测试 db-prep。当我在前钩子中使用 Done 时,Mocha 超时。
我收到的错误是“错误:超过 5000 毫秒的超时。对于异步测试和挂钩,请确保调用了“done()”;如果返回 Promise,请确保它已解决。(/Users/donfelipe/Sites/Agents/test/代理.js)"
已尝试将 done() 移动到 promise 链末尾的 finally 块中,但这只会导致 it 块在异步链完成执行之前运行。有点难过。
/*
test case to check that the get function returns
*/
process.env.NODE_ENV = 'test-db';
'use strict'
const mongoose = require("mongoose");
const schemas = require('../app_api/models/schemas');
const agents = require('../app_api/controllers/agents.js');
const lists = require('../app_api/controllers/lists.js');
const server = require('../app.js');
const assert = require('assert')
const config = require('config')
//Require the dev-dependencies
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
chai.use(chaiHttp);
describe('Agents test Suite', () => {
beforeEach(() => {
//don't have anything too do in this case
})
describe('/GET listAddItem suite', function () {
//before we can test deletion we have to add at least one list in.
const userModel = mongoose.model('User', schemas.userSchema);
const agentModel = mongoose.model('Agent', schemas.agentSchema);
let agentToAddId = {}
const listObject = {
listName: 'testList',
_id: mongoose.Types.ObjectId(),
agents: [{
_id: "00000000000000000000000",
name: "Test agent"
}]
}
const lengthToTestAgainst = listObject.agents.length
beforeEach((done) => {
userModel.findById(config.defaultUserId)
.select('agentList')
.then((parentDoc) => {
if (!parentDoc) {
console.error('Unable to find user');
}
parentDoc.agentList.push(listObject)
return parentDoc.save()
})
.then(() => {
return agentModel.find({})
})
.then((response) => {
agentToAddId = response[0]._id
//console.log(response[0]._id);
done()
})
})
it('should add a new item into the testList', (done) => {
chai.request(server)
.get(`/agents_api/listAddItem/${config.defaultUserId}/${listObject._id}/${agentToAddId}`)
.end((err, response) => {
response.should.have.status(200)
response.body.agentList.testList.should.not.be.equal(lengthToTestAgainst + 1)
done(err)
})
})
})
})
解决方案
呃。自己解决了这个问题。尾巴摇狗的真实案例。所以我模拟了 chai.request(server) 对 API 的调用:
/agents_api/listAddItem/${config.defaultUserId}/${listObject._id}/${agentToAddId}
并通过 POSTMAN 提交。原来 API 中有一个错误,所以它没有返回响应,所以我从 Mocha 得到的超时是一个有效的响应,请求只是挂起。
推荐阅读
- laravel - 如何使用 Carbon 'diffInDays' 在视图表中显示不同的值?
- react-native - 如何将 kleur@2.0.2 升级到 kleur3
- c++ - c++ 序列计算器 x_{n+1} = f (x_n),数学函数有问题
- angular - 角度应用程序在 prod 上抛出错误,但在 dev 上运行完美
- java - 用相应的 getter/setter 搜索/替换属性
- r - 使用 data.table 根据条件绑定行
- android - 是否可以在不访问 Internet 的情况下从应用程序下载 zip 文件?
- javascript - 为什么我不能分配 const 但我可以控制台记录它?
- angular - 单击时创建一个新的离子载玻片
- java - 构图:如何使形状的尺寸适合图像?