小编Pmi*_*its的帖子

用 Jest 模拟 mysql 连接

尝试测试如下所示的代码:

const mysql = require('mysql2/promise');

async myFunction () {

    const db = await mysql.createConnection(options);

    const results = await db.execute('SELECT `something` from `table`;');

    await db.end();
    
    // more code ...

}
Run Code Online (Sandbox Code Playgroud)

我需要以一种允许我使用它返回的任何内容来模拟对execute函数的调用的方式来模拟 mysql 连接。

我试过mysql2/promise模拟整个模块,但当然没有用,因为createConnection被模拟的没有返回任何可以调用该execute 函数的东西。我还尝试只模拟我需要的这 3 个函数,而不是模拟整个模块,例如:

jest.mock('mysql2/promise', () => ({
    createConnection: jest.fn(() => ({
        execute: jest.fn(),
        end: jest.fn(),
    })),
}));
Run Code Online (Sandbox Code Playgroud)

但这也不起作用。任何建议都非常感谢。

mysql unit-testing node.js jestjs

3
推荐指数
1
解决办法
4767
查看次数

标签 统计

jestjs ×1

mysql ×1

node.js ×1

unit-testing ×1