【问题标题】:Jest function not returning database query in the test, but yet adding to the actual databaseJest 函数在测试中未返回数据库查询,但尚未添加到实际数据库中
【发布时间】:2019-09-20 04:55:32
【问题描述】:

我无法让 Jest tesitng 函数从数据库调用中返回任何数据,也无法使用超测试 http 请求生成器库返回任何数据。

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);
    })
})

我期待测试函数中的数据库调用返回一些东西。但事实并非如此。但是在失眠测试时,它确实会向数据库中添加数据。

【问题讨论】:

  • expect(received).toBe(expected) // Object.is 相等 Expected: 200 Received: undefined 21 |控制台日志(响应); 22 | const res = await db.select('*').from('areacodes'); > 23 |期望(res.status).toBe(200); | ^ 24 | }) 25 | }) 26 |在 Object.toBe (_tests_/server.test.js:23:28)

标签: javascript node.js jestjs knex.js


【解决方案1】:

您可能在select 通话中遇到问题。我建议您使用Promise.then.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 对象,也许它一切正常,但它根本没有status 属性。

我已经阅读了 knex.js 文档,但在任何地方都找不到 status,所以这可能是问题所在。

【讨论】:

  • 出于某种原因,我尝试使用 .then() 语法,然后又回到异步等待语法。现在它从数据库查询中返回数据。 ``` it('get request /areacodes', async () => { try { const response = await db('areacodes').insert({areacode: 701, city: "Richmond", state: "VA"} ) console.log(response); const ac = await db.select('*').from('areacodes'); console.log('select response', ac); } catch(err) { console.log(错误);}```
  • 您确定数据库响应带有status 属性吗?我已经更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
相关资源
最近更新 更多