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