node.js - 单元测试 - 与 supertest 开 Jest 会超时

标签 node.js unit-testing express jestjs supertest

我运行单元测试时出错。我正在使用 NodeJS 的 Express 应用程序。我想测试返回消息 (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 运行 jest,模拟文件如下所示:

const rep={
    "lastname": "admin",
    "firstname": "admin",
    "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dece9e0e4e3cde8f9fee0f9e1a3eeec" rel="noreferrer noopener nofollow">[email protected]</a>",
    "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};

最佳答案

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

例如,在您的模拟文件中:

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

}

Controller

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

关于node.js - 单元测试 - 与 supertest 开 Jest 会超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53484391/

相关文章:

node.js - 不同步服务器响应

node.js - GraphQL Apollo 中的多对多关系

javascript - Node.js http - 将 GET 数据发送到服务器

django - django <-> 应用程序服务器(node.js)之间的通信方法?

java - 如何为 void 方法创建单元测试,该方法仅更改数据并保存它

c# - 使用 ISearchIndexClient 进行测试

sql - 在sqlite3中参数化 'limit'和 'order'

Node.js - 在路由中表达特殊字符 (/campañas)

typescript - 如何模拟 ServiceBusError 异常以进行 Jest 测试?

javascript - 无法访问在 Javascript 脚本标记内的 EJS 中声明的 json 数组的项目