单元测试-带有超级测试的笑话会导致超时

时间:2018-11-26 15:30:47

标签: node.js unit-testing express jestjs supertest

运行单元测试时出错。我正在使用NodeJS的快速应用程序。我想测试返回消息(200)和(最终)功能的输出。

const {Router} = require('express');
const {query} = require('../dbConfig');

module.exports = (router = new Router()) => {
    //get only one user from the id
    router.post('/getUser', async (req,res)=>{
        id = req.body.id;
        sql = "SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id=" + id;
        let result = await query(sql);
        if(result.length >= 1){
            res.send(result[0]);
        }

    })
    return router;
};

但是当我尝试运行以下测试时:

const app = require('../../app')
const request = require('supertest')
jest.mock('../../dbConfig');;

describe('POST /getUser', () => {
    let data = {
        id:1
    }

    it('Response 200 + response type',(done)=>{
        request.agent(app)
            .post('/getUser')
            .send(data)
            .expect(200, done)
    })
});

它向我返回以下错误

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

我尝试了不同的变体而没有成功...我也尝试了在线文档,但这对于解决此错误并没有真正的帮助...我用npx jest开玩笑,并且模拟文件看起来像这样:

const rep={
    "lastname": "admin",
    "firstname": "admin",
    "email": "admin@etsmtl.ca",
    "title_id": 1,
    "id": 1,
    "state": 1
};


const query = (sqli) =>{
    return new Promise((resolve, reject) =>{
        console.log("SQL request : " + sqli)
        if(sqli === "SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id=1"){
            console.log("Passed")
            resolve(rep);
        }
    });

}

module.exports = {query};

2 个答案:

答案 0 :(得分:1)

您的query方法返回一个对象(rep),然后在POST处理程序中检查其长度。对象的长度为undefined,因此不会达到res.send。您需要为另一个else设置一个res.send选项,这样无论发生什么情况,它都会回答客户端。另外,您可能想在if处理程序中更改该POST,或在模拟文件中更改返回格式。

例如,在您的Mock文件中:

const query = (sqli) =>{
    return new Promise((resolve, reject) =>{
        console.log("SQL request : " + sqli)
        if(sqli === "SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id=1"){
            console.log("Passed")
            resolve([rep]); //Now it's an array of length 1, reaches the first send
        } else {
            reject([]); //Length is 0, so it will reach the second send
        }
    });

}

控制器

if(result.length >= 1){
    res.send(result[0]);
} else {
    res.status(500).send('Something broke!');
}

答案 1 :(得分:0)

您确定数据库已初始化吗?您可以在控制器上尝试一下吗?

router.post('/getUser', async (req,res)=>{
    id = req.body.id;
    sql = "SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id=" + id;
    try {
       let result = await query(sql);
       if(result.length >= 1){
           res.send(result[0]);
       } else {
           res.sendStatus(404);
       }
    } catch(err) {
       res.sendStatus(500)
    }

})

如果您的数据库未正确初始化,或者查询抛出错误,它将永远不会响应