尝试测试如下所示的代码:
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)
但这也不起作用。任何建议都非常感谢。