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)
希望有更好的方法。
connection.query是 Nodejs 错误优先回调,您需要模拟它的实现并使用模拟错误或数据手动调用错误优先回调。
除非您需要绑定上下文,否则您不需要它。从你的问题来看,我不\xe2\x80\x99t看到绑定上下文的需要。
\n例如
\nfunc.js:
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;\nRun Code Online (Sandbox Code Playgroud)\nfunc.test.js:
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});\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1739 次 |
| 最近记录: |