Я пишу модульный тест для углового приложения, я проверяю, возвращает ли сервисная функция значение.
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'.
TopToolBarService.ts
import { EventEmitter, Injectable, Output } from "@angular/core";
@Injectable()
export class TopToolBarService {
customer = null;
getCustomer() {
return this.customer;
}
}