javascript - Jest - 如何使用模拟类实例

标签 javascript typescript testing jestjs auth0

在我的前端 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 上的某些方法。我该怎么做?

最佳答案

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

__mocks__/auth0-js.ts

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

代码.ts

import { WebAuth } from 'auth0-js'

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

代码.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 并使用它来检索已创建的实例。

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

关于javascript - Jest - 如何使用模拟类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56269566/

相关文章:

Javascript:消失的对象属性

typescript - 如何生成通用函数值?

ios - 如何调试 EarlGrey 测试中的超时失败?

javascript - 用json填充下拉列表

javascript - react 原生构建错误 : Attempt to invoke virtual method'boolean com. facebook.react.uimanager.FabricViewStateManager.hasStateWrappper()

javascript - 如何调用 tagit ("destroy") 来删除标签?

typescript - 如何在 beforeAll 测试中创建类型变量?

typescript - 从有区别的联合数组中查找的窄返回类型

javascript - react : How mock functions and test component rendering with jest:

testing - 什么是好的软件应用程序回归测试框架?