【问题标题】:Jest - how to use mocked class instanceJest - 如何使用模拟类实例
【发布时间】:2019-10-09 16:39:54
【问题描述】:

在我的前端 React 应用程序中,我使用 auth0-js 库进行身份验证。它导出WebAuth 类。在代码中,我通过调用WebAuth 创建了一个实例 像这样的:

import { WebAuth } from 'auth0-js'


const auth0Client = new WebAuth({ /* some options */ })

/* 
...
using auth0Client
...
*/

我在__mocks__ 文件夹中创建了一个与库名称一样的文件。多亏了这一点,Jest 自动模拟了这个库。

// __mocks__/auth0-js.ts
const auth0Mock = jest.genMockFromModule('auth0-js')

module.exports = auth0Mock

但是,在我的测试中,我想检查是否调用了 auth0Client 上的某些方法。我该怎么做?

【问题讨论】:

    标签: javascript typescript testing jestjs auth0


    【解决方案1】:

    这是一个简单的工作示例,可帮助您入门:

    __mocks__/auth0-js.ts

    module.exports = jest.genMockFromModule('auth0-js')
    

    code.ts

    import { WebAuth } from 'auth0-js'
    
    const auth0Client = new WebAuth({ domain: 'your domain', clientID: 'your client id'});
    auth0Client.authorize({ audience: 'your audience' });
    

    code.test.ts

    import { WebAuth } from 'auth0-js';
    import './code';  // <= run code.ts
    
    test('code', () => {
      expect(WebAuth).toHaveBeenCalledWith({ domain: 'your domain', clientID: 'your client id' });  // Success!
      const auth0Client = (WebAuth as jest.Mock).mock.instances[0];  // <= get the WebAuth instance
      expect(auth0Client.authorize).toHaveBeenCalledWith({ audience: 'your audience' });  // Success!
    })
    

    WebAuth 是一个模拟函数,所以当它用于创建一个新实例时,它会记录它创建的实例。

    在测试期间,您可以检索WebAuth 并使用它来检索已创建的实例。

    获得实例后,您可以检查它的函数(也包括模拟函数)以查看它们是否按预期调用。

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2019-03-22
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2017-09-30
      • 2019-08-10
      相关资源
      最近更新 更多