【问题标题】:Mocking the method of a class returned from an exported function模拟从导出函数返回的类的方法
【发布时间】:2026-02-13 22:20:02
【问题描述】:

我想模拟从模块导出返回的类的方法,我很难设置 Jest 测试来这样做。

这是我所拥有的:

// src/jwks.js

const jwksClient = require('jwks-rsa')
const client = jwksClient({...})
module.exports = client
// src/auth.js

const jwksClient = require('./jwks')

function getKey (header, callback) {
  jwksClient.getSigningKey(header.kid, function (err, key) {
    console.log("inside getSigningKey")
    var signingKey = key.publicKey || key.rsaPublicKey
    callback(err, signingKey)
  })
}

exports.getKey = getKey
// src/auth.test.js

const jwksClient = require('./jwks')
const { getKey } = require('./auth')

const mockGetSigningKey = jest.fn(() => {
    console.log("mockGetSigningKey called")
    return {
        publickey: "the-key"
    }
})

jest.mock('./jwks', () => {
  return jest.fn().mockImplementation(() => {
    return {
        getSigningKey: mockGetSigningKey
    }
  })
})

test('test mocked behavior', () => {
    getKey("somekey", (err, key) => {
        console.log("received key: " + key)
    })
}

我收到以下错误: TypeError: jwksClient.getSigningKey 不是函数

  2 | 
  3 | function getKey (header, callback) {
> 4 |   jwksClient.getSigningKey(header.kid, function (err, key) {
    |              ^
  5 |     console.log("inside getSigningKey")
  6 |     var signingKey = key.publicKey || key.rsaPublicKey
  7 |     callback(err, signingKey)

我该如何正确地做到这一点?我尝试了很多不同的变体,但没有一个对我有用。

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    您没有正确模拟 ./jwks 模块。这是解决方案:

    auth.js:

    const jwksClient = require('./jwks');
    
    function getKey(header, callback) {
      jwksClient.getSigningKey(header.kid, function (err, key) {
        console.log('inside getSigningKey');
        var signingKey = key.publicKey || key.rsaPublicKey;
        callback(err, signingKey);
      });
    }
    
    exports.getKey = getKey;
    

    jwks.js:

    // whatever
    

    auth.test.js:

    const { getKey } = require('./auth');
    const jwksClient = require('./jwks');
    
    jest.mock('./jwks', () => {
      return { getSigningKey: jest.fn() };
    });
    
    describe('62544352', () => {
      it('should pass', () => {
        jwksClient.getSigningKey.mockImplementationOnce((key, callback) => {
          const key = { publicKey: 'publicKey' };
          callback(null, key);
        });
        const mCallback = jest.fn();
        getKey({ kid: 'someKey' }, mCallback);
        expect(jwksClient.getSigningKey).toBeCalledWith('someKey', expect.any(Function));
        expect(mCallback).toBeCalledWith(null, 'publicKey');
      });
    });
    

    带有覆盖率报告的单元测试结果:

     PASS  */62544352/auth.test.js (10.232s)
      62544352
        ✓ should pass (28ms)
    
      console.log
        inside getSigningKey
    
          at */62544352/auth.js:5:13
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |       50 |     100 |     100 |                   
     auth.js  |     100 |       50 |     100 |     100 | 6                 
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        11.65s
    

    【讨论】:

    • 啊,好接棒!像魅力一样工作。非常感谢。
    最近更新 更多