[英]How to spy service method in angular 4 jasmine test cases
I want to spy a method in service which is injected into the angular component. 我想在使用中侦察一种方法,该方法被注入到角度组件中。
My method in the component which I want to test is : 我要测试的组件中的方法是:
validateLogin() {
console.log("Before calling validateLogin method,", this.form.value.Username, this.form.value.Password);
this.loginService.validateLogin(this.form.value.Username, this.form.value.Password)
.then(response => {
console.log("Response,", response);
if(response.SkipWelcomePage) {
this.router.navigateByUrl("/");
}
else this.router.navigateByUrl("/welcome");
})
.catch(err => {
this.errorMessage = err;
});
}
My test case for above method is : 我的上述方法的测试用例是:
it('should validate login', async(() => {
const loginService = fixture.debugElement.injector.get(LoginService);
spyOn(loginService,'validateLogin').and.returnValue(function (username, password) {
return {SkipWelcomePage: false}
});
fixture.componentInstance.form.controls['Username'].setValue("test");
fixture.componentInstance.form.controls['Password'].setValue("test");
fixture.detectChanges();
fixture.debugElement.query(By.css('.loginButton')).nativeElement.click();
expect(routerStub.navigate).toHaveBeenCalledWith(['/welcome']);
}));
The test case is getting failed and the console log : console.log("Response,", response);
测试用例失败,控制台日志为: console.log("Response,", response);
is not getting displayed and also there is no error in the console. 不会显示,并且控制台中也没有错误。
How can i resolve this issue? 我该如何解决这个问题?
First a bit of cleaner code. 首先是一些更简洁的代码。 It looks like you want to stub out the login service entirely, instead of using the real one and mocking a function. 似乎您想完全保留登录服务,而不是使用真正的登录服务并模拟功能。
Define an object in your initial setup called 'loginServiceMock': 在初始设置中定义一个名为“ loginServiceMock”的对象:
const loginServiceMock = jasmine.createSpyObj('LoginService', ['validateLogin']);
Then, in your list of providers, add: 然后,在提供商列表中,添加:
{provide: LoginService, useValue: loginServiceMock}
Then the problem you're having. 然后是您遇到的问题。 LoginService should return a Promise object, not a plain Typescript object, since you're calling the '.then()' on its result. LoginService应该返回Promise对象,而不是普通的Typescript对象,因为您要在其结果上调用'.then()'。 What you'll want to do is something like: 您想要做的是这样的:
loginServiceMock.validateLogin.and.returnValue(Promise.resolve({SkipWelcomePage: false});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.