作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为角度应用程序编写单元测试,正在测试服务功能是否返回值。
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
}))
bDefine = false;
ngOnInit() {
let customer = this.topToolBarService.getCustomer();
if (customer == null) {
bDefine = false;
} else {
bDefine = true;
}
}
import { EventEmitter, Injectable, Output } from "@angular/core";
@Injectable()
export class TopToolBarService {
customer = null;
getCustomer() {
return this.customer;
}
}
最佳答案
尝试更新beforeEach(async(()=> ...)内的提供程序,并将您的mockedService变量移至其顶部:
describe('Component TEST', () => {
...
let mockToolBarService;
...
beforeEach(async(() => {
...
mockToolBarService = jasmine.createSpyObj(['getCustomer']);
mockToolBarService.getCustomer.and.returnValue('king');
TestBed.configureTestingModule ({
...
providers: [ { provide: TopToolBarService, useValue: mockToolBarService } ]
...
关于angular - 如何在Angular组件中模拟服务功能以进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331328/
我是一名优秀的程序员,十分优秀!