我正在尝试为 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'
});
});
});
如果我将模拟移入测试本身,它就会停止工作。我想使用模拟编写更多测试,但不确定如何执行此操作。任何帮助深表感谢!
慕标琳琳
相关分类