connection.query
是 Nodejs 错误优先回调,您需要模拟它的实现并使用模拟的错误或数据手动调用错误优先回调。
除非您需要绑定上下文,否则您不需要它。从您的问题来看,我认为不需要绑定上下文。
例如
func.js
:
const util = require('util');
async function fun(conn, input) {
const connection = conn.getConnection();
const processed_input = 'processed ' + input;
const x = util.promisify(connection.query).bind(connection);
return x(processed_input);
}
module.exports = fun;
func.test.js
:
const fun = require('./func');
describe('67774122', () => {
it('should pass', async () => {
const mConnection = {
query: jest.fn().mockImplementation((input, callback) => {
callback(null, 'mocked query result');
}),
};
const mConn = {
getConnection: jest.fn().mockReturnValueOnce(mConnection),
};
const actual = await fun(mConn, 'input');
expect(actual).toEqual('mocked query result');
expect(mConn.getConnection).toBeCalledTimes(1);
expect(mConnection.query).toBeCalledWith('processed input', expect.any(Function));
});
});
测试结果:
PASS examples/67774122/func.test.js (7.015 s)
67774122
✓ should pass (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
func.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.52 s