Javascript Jest函数在测试中不返回数据库查询,而是添加到实际数据库中
我无法让Jest tesitng函数从数据库调用或使用supertest http请求生成器库返回任何数据Javascript Jest函数在测试中不返回数据库查询,而是添加到实际数据库中,javascript,node.js,jestjs,knex.js,Javascript,Node.js,Jestjs,Knex.js,我无法让Jest tesitng函数从数据库调用或使用supertest http请求生成器库返回任何数据 describe('API calls', () => { it('testing jest', () => { expect(2).toBe(2); }) it('get request /areacodes', async () => { const response = await db('areacodes
describe('API calls', () => {
it('testing jest', () => {
expect(2).toBe(2);
})
it('get request /areacodes', async () => {
const response = await db('areacodes').insert({areacode: 804, city: "Richmond", state: "VA"})
console.log(response);
const res = await db.select('*').from('areacodes');
expect(res.status).toBe(200);
})
})
我希望测试函数中的数据库调用返回一些东西。但事实并非如此。它确实会将数据添加到数据库中,但是在失眠测试时。您在
选择调用中可能会遇到一些问题。我建议您使用承诺。然后.catch
块尝试查找错误:
db('areacodes').insert({areacode: 804, city: 'Richmond', state: 'VA'}).then((response) => {
console.log(response);
db.select('*').from('areacodes').then((res) => {
expect(res.status).toBe(200);
}).catch((error) => {
console.log(error);
});
}).catch((error) => {
console.log(error);
});
另外,您应该检查res
对象,也许它工作正常,但它没有状态
属性
我已经阅读了knex.js文档,但我在任何地方都找不到状态
,所以可能这就是问题所在。expect(received).toBe(expected)//Object.is equality expected:200 received:undefined 21 | console.log(response);22 | const res=wait db.select('*')。from('areacodes');>23 | expect(res.status)toBe(200)|24 |})25 |})26 |在Object.toBe(_tests_/server.test.js:23:28)出于某种原因,我尝试使用.then()语法,然后返回到异步等待语法。现在它从数据库查询返回数据它('get request/areacodes',async()=>{try{const response=await db('areacodes')。插入({areacode:701,城市:“里士满”,州:“VA”})console.log(响应);const ac=await db.select('*')。from('areacodes');console.log('select response',ac);}catch(错误){console.log(err);}``您确定数据库响应带有status
属性吗?我已更新了答案。