【问题标题】:How to mock a promisified and binded function in JEST?如何在 JEST 中模拟一个承诺和绑定的函数?
【发布时间】:2021-08-18 18:47:10
【问题描述】:

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

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);
}

我希望将 processed_input 的值传递给函数 x

我认为像 .toHaveBeenCalledWith 这样的东西应该可以工作我不确定它对于承诺的绑定函数是如何工作的。

我还尝试在fun 调用之前模拟查询,例如conn.getConnection = { query: jest.fn() },但我不确定如何继续使用expect

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

conn.getConnection = {
 query: function(processed_input){ //expect processed_input to be; } 
}`

希望有更好的方法。

【问题讨论】:

    标签: node.js unit-testing jestjs mocking node-promisify


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2020-10-07
      • 2021-11-04
      • 1970-01-01
      • 2020-02-15
      • 2017-02-26
      • 2021-04-19
      相关资源
      最近更新 更多