gpt4 book ai didi

angular - 如何在Angular组件中模拟服务功能以进行单元测试

转载 作者:行者123 更新时间:2023-12-02 02:42:36 26 4
gpt4 key购买 nike

我正在为角度应用程序编写单元测试,正在测试服务功能是否返回值。

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;
}
}

我相信我在测试中 mock 了服务功能,因此我希望它必须到达变量设置为“true”的其他部分。

TopToolBarService.ts
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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com