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

Jest Mocks 在调用 Mocks 时未在 expect().toBeCalled()

Jest Mocks 在调用 Mocks 时未在 expect().toBeCalled()

米琪卡哇伊 2023-03-24 15:28:05
对于有问题的测试,我模拟了一些回调并将它们传递给我正在测试的函数。我在模拟中添加了 console.log 只是为了尝试调试正在发生的事情。这些 console.log 正在测试日志中打印出来,因此看起来好像模拟回调实际上在测试期间被正确调用(请参阅下面的测试输出)但是当我执行 expect(mockedFunction).toBeCalled() 时断言失败。我不明白为什么它会失败,因为模拟回调在测试运行时注销到控制台。这是我的代码:这是我要测试的代码。import IAccount from './IAccount';import IAccountManager from './IAccountManager';import firebase from '../firebase/Firebase';import { stringHasASymbol } from '../../common/Utility';export class FirebaseAccountManager implements IAccountManager {  register(newAccount: IAccount, successCallback: (response: any) => any, errorCallback: (error: any) => any): void {    console.log("called: FirebaseAccountManager:register()");    firebase.register(newAccount.email, newAccount.password, newAccount.firstName + " " + newAccount.lastName)      .then(response => {        console.log("GOT HERE 1", response)        successCallback(true);      })      .catch(error => {        console.log("GOT HERE 2", error)        errorCallback({ code: this.convertRegisterErrorCode(error.code), message: error.message })      });  }  private convertRegisterErrorCode(code: string): string {    if (code === 'auth/email-already-in-use') {      return 'email-already-in-use';    }    return 'unsupported-error-type: firebase error code = ' + stringHasASymbol;  }}这是我的测试:import { FirebaseAccountManager } from './FirebaseAccountManager';import IAccount from './IAccount';jest.mock('firebase/app', () => (  {    auth: jest.fn().mockReturnThis(),    initializeApp: jest.fn(),    createUserWithEmailAndPassword: jest.fn()      .mockResolvedValueOnce(true)      .mockRejectedValueOnce({        code: 'invalid-email'      })  }));const mockSuccessCallback = jest.fn((response: any) => {  console.log("MOCK SUCCESS CALLBACK CALLED", response);  return 'Success!';});const mockErrorCallback = jest.fn((error: any) => {  console.log("MOCK ERROR CALLBACK CALLED", error);  return { code: 'invalid-email', message: 'this email is already in use' }});afterEach(() => {  jest.clearAllMocks();});});
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

我解决了这个。问题是 FirebaseAccountManager 中的注册函数正在处理一个承诺,但不是异步的。一旦我将异步添加到函数并在测试中等待它,测试就通过了。我认为测试断言在承诺解决或拒绝它之前调用了回调。更新代码示例如下:


  async register(newAccount: IAccount, successCallback: (response: any) => any, errorCallback: (error: any) => any): Promise<any> {

    console.log("called: FirebaseAccountManager:register()");

    await firebase.register(newAccount.email, newAccount.password, newAccount.firstName + " " + newAccount.lastName)

      .then(response => {

        console.log("GOT HERE 1", response)

        successCallback(true);

      })

      .catch(error => {

        console.log("GOT HERE 2", error)

        errorCallback({ code: this.convertRegisterErrorCode(error.code), message: error.message })

      });

  }

这是现在通过的更改测试。


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

    console.log("START Successful Registration")

    const newAccount: IAccount = { firstName: 'asdf', lastName: 'asdf', email: 'asdf@adf.com', password: 'qwer', phoneNumber: '', workStatus: '', city: '', postalCode: '', country: '' }


    const fam = new FirebaseAccountManager();

    await fam.register(newAccount, mockSuccessCallback, mockErrorCallback);

    expect(mockSuccessCallback).toBeCalled();

    expect(mockErrorCallback).not.toBeCalled();

    console.log("DONE Successful Registration")

  });


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

    console.log("START Failed Registration")

    const newAccount: IAccount = { firstName: 'asdf', lastName: 'asdf', email: 'asdf@adf.com', password: 'qwer', phoneNumber: '', workStatus: '', city: '', postalCode: '', country: '' }


    const fam = new FirebaseAccountManager();

    await fam.register(newAccount, mockSuccessCallback, mockErrorCallback);

    expect(mockSuccessCallback).not.toBeCalled();

    expect(mockErrorCallback).toBeCalled();

    console.log("DONE Failed Registration")

  });


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

添加回答

举报

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