Node.js Jest如何测试express API POST请求?
我需要使用Jest测试测试我对端点的POST请求是否正常工作。我的想法是首先获取服务表的计数(我正在使用sequelize orm),然后发送一个新的post请求,最后获取新的计数,并比较旧计数+1是否等于新计数,如果为真,则post请求工作正常Node.js Jest如何测试express API POST请求?,node.js,express,jestjs,Node.js,Express,Jestjs,我需要使用Jest测试测试我对端点的POST请求是否正常工作。我的想法是首先获取服务表的计数(我正在使用sequelize orm),然后发送一个新的post请求,最后获取新的计数,并比较旧计数+1是否等于新计数,如果为真,则post请求工作正常 test('Create a valid Service', async (done) => { const service = { name: "cool", description: "description" }; awa
test('Create a valid Service', async (done) => {
const service = {
name: "cool",
description: "description"
};
await Service.count().then(async function (count) {
await request(app)
.post('/api/services')
.send(service)
.then(async () => {
await Service.count().then(function (newcount) {
expect(newcount).toBe(count + 1);
});
})
.catch(err => console.log(`Error ${err}`));
});
}))
对我来说,测试看起来不错,但当我运行它时,我得到:
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
是否缺少某些内容,或者是否有更好的方法来测试POST请求?使用Jest?是因为您没有调用Jest回调函数中传递的done回调。可以这样做
test('Create a valid Service', async(done) => {
const service = {
name: "cool",
description: "description"
};
await Service.count().then(async function (count) {
await request(app)
.post('/api/services')
.send(service)
.then(async() => {
await Service.count().then(function (newcount) {
expect(newcount).toBe(count + 1);
// execute done callback here
done();
});
})
.catch(err => {
// write test for failure here
console.log(`Error ${err}`)
done()
});
});
});
您也可以用这种方式编写此代码,以便提高可读性并最大限度地利用异步/await
test('Create a valid Service', async(done) => {
const service = {
name: "cool",
description: "description"
};
try {
const count = await Service.count();
await request(app).post('/api/services').send(service)
const newCount = await Service.count()
expect(newCount).toBe(count + 1);
done()
} catch (err) {
// write test for failure here
console.log(`Error ${err}`)
done()
}
});
默认情况下,Jest还解析异步/等待情况下的承诺。我们也可以在不使用回调函数的情况下实现这一点
test('Create a valid Service', async() => {
const service = {
name: "cool",
description: "description"
};
try {
const count = await Service.count();
await request(app).post('/api/services').send(service)
const newCount = await Service.count()
expect(newCount).toBe(count + 1);
} catch (err) {
// write test for failure here
console.log(`Error ${err}`)
}
});
非常感谢你!请你投票表决我的问题好吗?