在我的前端 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/