我正在尝试使用 Mocha
和 Supertest
为我的 Node API 编写测试。
我成功地使用了 .then
的 promise ,但这很快就变成了“回调” hell ,很难长期维持。
// Success using `.then`
describe('/categories', () => {
it('GET-/categories ,should contain 2 category documents after creating', done => {
request(app)
.post('/categories')
.send({
name: 'user1',
})
.then(res => {
request(app)
.post('/categories')
.send({
name: 'user2',
})
.then(res => {
request(app)
.get('/categories')
.then(res => {
const categories = res.body;
expect(categories.length).to.equal(2);
done();
});
});
})
.catch(err => done(err));
});
});
现在我尝试用 async
await
编写它,但它返回一个错误。
// DOES NOT WORK using `async`/`await`
describe('/categories', () => {
it('GET-/categories ,should contain 2 category documents after creating', async done => {
try {
const category1 = await request(app)
.post('/categories')
.send({
name: 'user2',
});
const category2 = await request(app)
.post('/categories')
.send({
name: 'user2',
});
const categories = await request(app).get('/categories');
const result = categories.body;
expect(result.length).to.equal(2);
done();
} catch (e) {
done(e);
}
});
});
Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.
在研究这个问题时,我看到一些线程建议省略 done()
,所以我这样做了,但测试无法正常工作。他们甚至失败的断言也获得通过。
// DOES NOT WORK using `async`/`await` without `done()`
describe('/categories', () => {
it('GET-/categories ,should contain 2 category documents after creating', async () => {
try {
const category1 = await request(app)
.post('/categories')
.send({
name: 'user2',
});
const category2 = await request(app)
.post('/categories')
.send({
name: 'user2',
});
const categories = await request(app).get('/categories');
const result = categories.body;
expect(result.length).to.equal(2);
} catch (e) {
console.log(e);
}
});
});
最佳答案
好吧,我首先找到答案,你不应该使用 async 传递一个 did() 回调函数,然后使用 try-catch block 语句干扰断言,并且不让测试自然地进行。你可能最好不要将你的断言放在 catch-try 语句中!
it('GET-/categories ,should contain 2 category documents after creating',async()=>{
const category1 = await
request(app).post('/categories')
.send({
name :'user1'
});
const category2 = await
request(app).post('/categories')
.send({
name :'user2'
})
const result =await
request(app).get('/categories')
.set('Content-Type', 'application/json')
.set('Acccept', 'application/json')
.catch(err => {
throw err;
})
const categories= result.body;
expect(categories.length).to.equal(2);
})
关于node.js - 在带有 supertest 的 Mocha 断言中使用异步等待函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468033/