为了账号安全,请及时绑定邮箱和手机立即绑定

使用 jest.mock 进行多项测试

使用 jest.mock 进行多项测试

凤凰求蛊 2023-03-24 14:37:02
我正在尝试为 firebase auth createUserWithEmailAndPassword() 函数编写单元测试。我有一个我编写的帮助程序类调用此函数并返回一个承诺。我试图在我的测试中模拟 firebase createUserWithEmailAndPassword() 函数并且它有效但仅适用于一个测试用例。我不知道如何为其他测试用例更改 createUserWithEmailAndPassword() 的模拟。我使用 jest.fn().mockRejectedValueOnce() 来拒绝承诺并返回错误代码。我想做的是重新模拟 mockRejectdValueOnce() 来处理备用错误代码和 mockResolveValueOnce() 来处理成功的案例。我试过将 jest.mock(...) 移动到测试本身,但模拟不再有效,而是调用真实函数。这是我的助手类import app from 'firebase/app';import 'firebase/auth';const config = {  apiKey: "somevalue",  authDomain: "somevalue",  databaseURL: "somevalue",  projectId: "somevalue",  storageBucket: "somevalue",  messagingSenderId: "somevalue",  appId: "somevalue",  measurementId: "somevalue"};class Firebase {  private auth: app.auth.Auth;  constructor() {    app.initializeApp(config);    this.auth = app.auth();  }  public async register(email: string, password: string, name: string): Promise<any> {    return await this.auth.createUserWithEmailAndPassword(email, password);  }}export default new Firebase();这是我编写的有效测试:import { FirebaseAccountManager } from './FirebaseAccountManager';import IAccount from './IAccount';jest.mock('firebase/app', () => (  {    auth: jest.fn().mockReturnThis(),    initializeApp: jest.fn(),    createUserWithEmailAndPassword: jest.fn().mockRejectedValueOnce({      code: 'auth/invalid-email'    }),  }));describe('test', () => {  test('aTest', async () => {    const newAccount: IAccount = { firstName: 'asdf', lastName: 'asdf', email: 'asdf.adf.com', password: 'qwer', phoneNumber: '', workStatus: '', city: '', postalCode: '', country: '' }    const fam = new FirebaseAccountManager();    await expect(fam.register(newAccount)).rejects.toEqual({      code: 'auth/invalid-email'    });  });});如果我将模拟移入测试本身,它就会停止工作。我想使用模拟编写更多测试,但不确定如何执行此操作。任何帮助深表感谢!
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

不确定它是否正是您要查找的内容,但一种方法是链接多个mockResolvedValueOnce和mockRejectedValueOnce调用而不是单个调用,无论您希望在测试中使用它们的顺序如何。


从文档:


test('async test', async () => {

  const asyncMock = jest

    .fn()

    .mockResolvedValue('default')

    .mockResolvedValueOnce('first call')

    .mockResolvedValueOnce('second call');


  await asyncMock(); // first call

  await asyncMock(); // second call

  await asyncMock(); // default

  await asyncMock(); // default

});


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信