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

对于有问题的测试,我模拟了一些回调并将它们传递给我正在测试的函数。我在模拟中添加了 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();

});


});


米琪卡哇伊
浏览 76回答 1
1回答

慕田峪7331174

我解决了这个。问题是 FirebaseAccountManager 中的注册函数正在处理一个承诺,但不是异步的。一旦我将异步添加到函数并在测试中等待它,测试就通过了。我认为测试断言在承诺解决或拒绝它之前调用了回调。更新代码示例如下:&nbsp; async register(newAccount: IAccount, successCallback: (response: any) => any, errorCallback: (error: any) => any): Promise<any> {&nbsp; &nbsp; console.log("called: FirebaseAccountManager:register()");&nbsp; &nbsp; await firebase.register(newAccount.email, newAccount.password, newAccount.firstName + " " + newAccount.lastName)&nbsp; &nbsp; &nbsp; .then(response => {&nbsp; &nbsp; &nbsp; &nbsp; console.log("GOT HERE 1", response)&nbsp; &nbsp; &nbsp; &nbsp; successCallback(true);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch(error => {&nbsp; &nbsp; &nbsp; &nbsp; console.log("GOT HERE 2", error)&nbsp; &nbsp; &nbsp; &nbsp; errorCallback({ code: this.convertRegisterErrorCode(error.code), message: error.message })&nbsp; &nbsp; &nbsp; });&nbsp; }这是现在通过的更改测试。&nbsp; test('Successful Registration', async () => {&nbsp; &nbsp; console.log("START Successful Registration")&nbsp; &nbsp; const newAccount: IAccount = { firstName: 'asdf', lastName: 'asdf', email: 'asdf@adf.com', password: 'qwer', phoneNumber: '', workStatus: '', city: '', postalCode: '', country: '' }&nbsp; &nbsp; const fam = new FirebaseAccountManager();&nbsp; &nbsp; await fam.register(newAccount, mockSuccessCallback, mockErrorCallback);&nbsp; &nbsp; expect(mockSuccessCallback).toBeCalled();&nbsp; &nbsp; expect(mockErrorCallback).not.toBeCalled();&nbsp; &nbsp; console.log("DONE Successful Registration")&nbsp; });&nbsp; test('Failed Registration', async () => {&nbsp; &nbsp; console.log("START Failed Registration")&nbsp; &nbsp; const newAccount: IAccount = { firstName: 'asdf', lastName: 'asdf', email: 'asdf@adf.com', password: 'qwer', phoneNumber: '', workStatus: '', city: '', postalCode: '', country: '' }&nbsp; &nbsp; const fam = new FirebaseAccountManager();&nbsp; &nbsp; await fam.register(newAccount, mockSuccessCallback, mockErrorCallback);&nbsp; &nbsp; expect(mockSuccessCallback).not.toBeCalled();&nbsp; &nbsp; expect(mockErrorCallback).toBeCalled();&nbsp; &nbsp; console.log("DONE Failed Registration")&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript