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

kar*_*sys 18 unit-testing typescript angular

我正在为 angular 应用程序编写单元测试,我正在测试服务函数是否返回一个值。

组件.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
  }))

Run Code Online (Sandbox Code Playgroud)

组件.ts

bDefine = false;
ngOnInit() {
 let customer = this.topToolBarService.getCustomer();
 if (customer == null) {
   bDefine = false;
 } else {
    bDefine = true;
   }
}
Run Code Online (Sandbox Code Playgroud)

我相信我已经在我的测试中模拟了服务功能,所以我希望它一定已经到达变量设置为“true”的其他部分。

TopToolBarService.ts

import { EventEmitter, Injectable, Output } from "@angular/core";

@Injectable()
export class TopToolBarService {
customer = null;

  getCustomer() {
    return this.customer;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 12

尝试在 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 } ]
           ...
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Isl*_*aev 6

更改您的供应商价值

beforeEach(() => {
   TestBed.configureTestingModule({
      declarations: [ UsersListComponent],
      providers: [{
         provide: TopToolBarService,
         useValue: jasmine.createSpyObj('TopToolBarService', ['getCustomer'])
      }],
      schemas:[CUSTOM_ELEMENTS_SCHEMA]
     });
     mockTopToolBarService = TestBed.get(TopToolBarService);

     mockTopToolBarService.getCustomer.and.returnValue(of([])); // mock output of function
   })

Run Code Online (Sandbox Code Playgroud)


obs*_*eam 1

您必须在运行代码之前配置测试模块。它不知道您的间谍对象,除非您将其TestBed.configureTestingModule作为导入传递给。

https://angular.io/guide/testing#component-with-a-dependency