如何在 JEST 中模拟承诺和绑定的函数?

Anu*_*rix 3 unit-testing mocking node.js jestjs node-promisify

我需要开玩笑地为一个函数编写一个测试。我有如下功能:

async function fun(conn, input){
    const connection = conn.getConnection();
    ....
    // some output gets generated from input 
    // const processed_input = input???;
    ....
    const x = util.promisify(connection.query).bind(connection);
    return /* await */ x(processed_input);
}
Run Code Online (Sandbox Code Playgroud)

我希望将其值processed_input传递给 function x

我认为类似的东西.toHaveBeenCalledWith应该有效,但我不确定它如何适用于承诺的绑定函数。

我还尝试模拟查询,执行类似于调用conn.getConnection = { query: jest.fn() }之前的fun操作,但我不确定如何继续进行expect

expect更新:到目前为止,我当前的解决方案是在查询函数中包含 jest语句。

conn.getConnection = {
 query: function(processed_input){ //expect processed_input to be; } 
}`
Run Code Online (Sandbox Code Playgroud)

希望有更好的方法。

sli*_*wp2 6

connection.query是 Nodejs 错误优先回调,您需要模拟它的实现并使用模拟错误或数据手动调用错误优先回调。

\n

除非您需要绑定上下文,否则您不需要它。从你的问题来看,我不\xe2\x80\x99t看到绑定上下文的需要。

\n

例如

\n

func.js

\n
const util = require(\'util\');\n\nasync function fun(conn, input) {\n  const connection = conn.getConnection();\n  const processed_input = \'processed \' + input;\n  const x = util.promisify(connection.query).bind(connection);\n  return x(processed_input);\n}\n\nmodule.exports = fun;\n
Run Code Online (Sandbox Code Playgroud)\n

func.test.js

\n
const fun = require(\'./func\');\n\ndescribe(\'67774122\', () => {\n  it(\'should pass\', async () => {\n    const mConnection = {\n      query: jest.fn().mockImplementation((input, callback) => {\n        callback(null, \'mocked query result\');\n      }),\n    };\n    const mConn = {\n      getConnection: jest.fn().mockReturnValueOnce(mConnection),\n    };\n    const actual = await fun(mConn, \'input\');\n    expect(actual).toEqual(\'mocked query result\');\n    expect(mConn.getConnection).toBeCalledTimes(1);\n    expect(mConnection.query).toBeCalledWith(\'processed input\', expect.any(Function));\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

测试结果:

\n
 PASS  examples/67774122/func.test.js (7.015 s)\n  67774122\n    \xe2\x9c\x93 should pass (4 ms)\n\n----------|---------|----------|---------|---------|-------------------\nFile      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------|---------|----------|---------|---------|-------------------\nAll files |     100 |      100 |     100 |     100 |                   \n func.js  |     100 |      100 |     100 |     100 |                   \n----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        7.52 s\n
Run Code Online (Sandbox Code Playgroud)\n