Angular2测试服务模拟 [英] Angular2 testing service mocks
问题描述
我有一个简单的Angular2组件,由以下组成
I have a simple Angular2 component that consists of the following
import { Component, OnInit, Input } from '@angular/core';
import {FooterLinksService} from './footer-links.service';
import { environment } from '../../environments/environment';
@Component({
selector: 'app-footer-links',
templateUrl: './footer-links.component.html',
styleUrls: ['./footer-links.component.css'],
providers: [FooterLinksService]
})
export class FooterLinksComponent implements OnInit {
constructor(private footerLinksService: FooterLinksService) {
let footerLinks = this.footerLinksService.LoadFooterLinks();
}
}
我正在尝试写单位用Jasmine测试这个。现在我想模拟FooterLinksService,但我见过的大多数例子都涉及手动编写FooterLinksServiceMock。有没有其他方法我可以使用自动生成模拟服务,如NSubStitute,我提供了预期的返回值来自footerLinksService.LoadFooterLinks
I am trying to write the unit tests with Jasmine for this. Now I want to mock the FooterLinksService, but most of the examples I have seen involve manually writing a FooterLinksServiceMock. Is there any other approach I can use which autogenerates the mock service like NSubStitute and I provide the expected returns values from footerLinksService.LoadFooterLinks
推荐答案
正如@JBNizet所提到的,你可以使用间谍。你要做的是获得测试中的实际服务,然后你可以监视一个方法,当调用该方法时,返回任意值。它可能看起来像
As mentioned by @JBNizet, you could just use a spy. What you would do is get the actual service inside the test, then you can spy on a method an return any arbitrary value, when that method is called. It might look something like
describe('component: FooterLinksComponent', () => {
let fixture;
let service;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
FooterLinksComponent
],
});
fixture = TestBed.createComponent(FooterLinksComponent);
service = fixture.debugElement.injector.get(FooterLinksService);
});
it('should change message returned', () => {
spyOn(service, 'LoadFooterLinks').and.returnValue('Hello new message');
fixture.detectChanges();
expect(fixture.componentInstance.message).toBe('Hello new message');
});
});
您需要将构造函数内部访问服务的代码移动到 ngOnInit
。原因是因为
You will need to move the code where you access the service from inside the constructor into the ngOnInit
. The reason for this is because
- 您使用的是
@ Component.providers
,所以在创建组件之前,不会创建服务。 - 创建组件时,已经调用了构造函数。所以这并没有给你时间来设置间谍。当您使用
ngOnInit
时,在您调用fixture.detectChanges()之前,不会调用
ngOnInit
- You are using
@Component.providers
, so the service will not be created until the component is created. - When the component is created, the constructor is already called. So this doesn't give time for you to set up the spy. When you use
ngOnInit
, thengOnInit
is not called until you callfixture.detectChanges()
这篇关于Angular2测试服务模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!