【问题标题】:Using jest.mock for multiple tests使用 jest.mock 进行多个测试
【发布时间】:2020-09-23 18:49:42
【问题描述】:

我正在尝试为 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'
    });

  });
});

如果我将模拟移动到测试本身,它就会停止工作。我想使用模拟编写更多测试,但不知道该怎么做。非常感谢任何帮助!

【问题讨论】:

    标签: javascript firebase-authentication jestjs mocking


    【解决方案1】:

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

    来自docs

    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
    });
    

    【讨论】:

    • 这可行,但没有办法在测试中指定模拟?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多