亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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: '[email protected]', 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: '[email protected]', 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 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號