如何在Angular组件中模拟服务功能以进行单元测试
问题描述:
我正在为angular应用编写单元测试,正在测试服务函数是否返回值.
I am writing unit test for angular app, I am testing if the service function returns a value.
component.spec.ts
import {TopToolBarService} from '../../top-toolbar/top-toolbar.service';
beforeEach(async(() => {
TestBed.configureTestingModule ({
declarations: [ UsersListComponent],
providers: [TopToolBarService],//tried mocking service here,still test failed
schemas:[CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should return data from service function', async(() => {
let mockTopToolBarService: jasmine.SpyObj<TopToolBarService>;
mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
mockTopToolBarService.getCustomer.and.returnValue("king");
fixture.detectChanges();
expect(component.bDefine).toBe(true); //fails
}))
component.ts
bDefine = false;
ngOnInit() {
let customer = this.topToolBarService.getCustomer();
if (customer == null) {
bDefine = false;
} else {
bDefine = true;
}
}
我相信我在测试中嘲笑了服务函数,因此我希望它必须到达变量设置为"true"的其他部分.
I believe I have mocked the service function in my test, so I expect it must have reached else part where variable is set to 'true'.
TopToolBarService.ts
import { EventEmitter, Injectable, Output } from "@angular/core";
@Injectable()
export class TopToolBarService {
customer = null;
getCustomer() {
return this.customer;
}
}
答
尝试更新beforeEach(async(()=> ...)内的提供程序,并将您的mockedService变量移至其顶部:
Try updating providers inside beforeEach(async(() => ...) and moving your mockedService variable on the top of it:
describe('Component TEST', () => {
...
let mockToolBarService;
...
beforeEach(async(() => {
...
mockToolBarService = jasmine.createSpyObj(['getCustomer']);
mockToolBarService.getCustomer.and.returnValue('king');
TestBed.configureTestingModule ({
...
providers: [ { provide: TopToolBarService, useValue: mockToolBarService } ]
...
希望有帮助!