我的服务中有一个要测试的方法register()
。我的断言是,从注入的服务调用了另一个方法。让我们更深入地研究我的代码:
export class OAuthRegistrationService {
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore) {
}
public register(register: RegisterDataModel): Promise<void | string> {
return this.afAuth.auth.createUserWithEmailAndPassword(register.email, register.password)
.then(() => {
const user = this.afAuth.auth.currentUser;
this.setUser(user, register).then(() =>
user.sendEmailVerification().then(() => 'Please verify your email').catch((err) => err));
}).catch((err: FirebaseErrorModel) => err.message);
}
}
现在在单元测试中,我想断言sendEmailVerification
已被调用。现在,我需要正确模拟上面调用的pomis,以检查是否已调用此方法。
describe('OAuthRegistrationService', () => {
let service: OAuthRegistrationService;
// stubs
const afAuthStub = {
auth: {
sendEmailVerification(): Promise<void> {
return new Promise<void>(resolve => resolve());
},
createUserWithEmailAndPassword(): Promise<void> {
return new Promise<void>(resolve => resolve());
},
currentUser: {
uid: 'blub'
}
}
};
const afsStub = {
doc(path: string) {
return {
set() {
return path;
}
};
}
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: AngularFireAuth, useValue: afAuthStub},
{provide: AngularFirestore, useValue: afsStub},
OAuthRegistrationService
]
});
service = TestBed.get(OAuthRegistrationService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should send email verification', () => {
const register: RegisterDataModel = new RegisterDataModel('username', 'abc@email.com', 'password', null, null);
const mock = TestBed.get(AngularFireAuth);
const spy = spyOn(afAuthStub.auth, 'sendEmailVerification').and.callThrough();
spyOn(afAuthStub.auth, 'createUserWithEmailAndPassword').and.callThrough();
mock.auth = afAuthStub.auth;
service.register(register).then(() => {
expect(spy).toHaveBeenCalled();
});
});
});
茉莉花and.callTrough
允许我调用Promise .then()
方法并转到测试方法的下一步。但是控制台以某种方式说:我的间谍从未被调用过。有人知道吗,我在这里做什么错了?
答案 0 :(得分:1)
您的存根稍有不正确,sendEmailVerification()
方法属于currentUser
属性。
const afAuthStub = {
auth: {
createUserWithEmailAndPassword(): Promise<void> {
return new Promise<void>(resolve => resolve());
},
currentUser: {
uid: 'blub',
sendEmailVerification(): Promise<void> {
return new Promise<void>(resolve => resolve());
},
}
}
};
...
const spy = spyOn(afAuthStub.auth.currentUser, 'sendEmailVerification')
这里是StackBlitz,测试通过。