[英]Angular + Jasmine: How to ignore/ mock one function in the tested component (not in a dependency)?
[英]Angular2 - Call function from a tested component
我目前正在使用Karma和Jasmine编写Angular2的单元测试,但是我在单元测试方面还很陌生,并且遇到了一些困难。 在测试硬编码属性或不涉及异步函数的属性时,都可以,但是我需要能够调用组件的函数以使某些变量获取其值。 我在做什么如下:
我的组件:
export class LoginComponent implements OnInit {
formLoginId: string;
loginUrl: string;
email: string;
password: string;
constructor(private googleAuthService: GoogleAuthService,
private authService: AuthenticationService,
private validationService: ValidationService,
private router: Router,
private titleService: Title) {
this.titleService.setTitle("Login");
this.formLoginId = "#form-login";
}
ngOnInit() {
this.googleAuthService.getLink((response) => {
this.loginUrl= response.json().url;
});
}
login() {
if (this.validationService.isValid(this.formLoginId)) {
this.authService.login(this.email, this.password);
}
}
现在,我想编写一个单元测试,它可以检查loginUrl是否取任何值。 我的测试如下:
describe('Login Component', ()=> {
let component:LoginComponent;
let fixture:any;
beforeEach(async(()=> {
TestBed.configureTestingModule({
//declarations,imports and providers
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
}); /some-other-tests/
it('should have login url', fakeAsync(()=> {
component.ngOnInit();
tick(1000);
expect(component.loginUrl).toBeDefined();
}));
});
但似乎它不起作用。 对于所提到的变量,我仍然不确定。 如何从组件调用方法并在结果后检查变量?
谢谢!
在这种情况下,您需要模拟GoogleAuthService以返回一些信息,否则getLink将永远无法解析。
您可以为GoogleAuthService指定模拟提供程序,并使其返回已解决的可观察对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.