Programing

단위시험을 위한 각도부재에서의 모의서비스 기능

c10106 2022. 3. 13. 10:28
반응형

단위시험을 위한 각도부재에서의 모의서비스 기능

각 앱에 대한 단위 테스트를 작성 중인데, 서비스 기능이 값을 반환하는지 테스트하고 있어.

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

구성 요소.ts

bDefine = false;
ngOnInit() {
 let customer = this.topToolBarService.getCustomer();
 if (customer == null) {
   bDefine = false;
 } else {
    bDefine = true;
   }
}

내 시험에서 서비스 기능을 조롱한 것으로 생각되므로 변수가 '참'으로 설정된 다른 부분에 도달했을 것으로 예상한다.

TopToolBarService.ts

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

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

  getCustomer() {
    return this.customer;
  }
}

각(async(() =>)보다 먼저 제공자를 업데이트하고 그 위에 있는 모의 서비스 변수를 이동하십시오.

describe('Component TEST', () => {
   ...
   let mockToolBarService;
   ...
      beforeEach(async(() => {
      ...
      mockToolBarService = jasmine.createSpyObj(['getCustomer']);
      mockToolBarService.getCustomer.and.returnValue('king');
      TestBed.configureTestingModule ({
           ...
           providers: [ { provide: TopToolBarService, useValue: mockToolBarService } ]
           ...

도움이 되길 바래!

공급자 값 변경

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

@Pedro Bezanilla의 대답은 충분하다.단지 여기 더 적은 코드를 가진 다른 방법이 있다. 서비스가 싱글톤인 것을 고려하면, 대부분의 경우라고 생각한다.

차이점은 다음과 같은 제공자 구성이 제공되지 않는다는 것이다.configureTestingModule스파이는 에 의해 설치된다.spyOn대신 TestBed에서 가져온 서비스 객체에 대해.

호출TestBed.inject대신에TestBed.getv9.0.0 이후 더 이상 사용되지 않기 때문이다.

싱글톤 서비스의 경우, 여기 Angle 웹사이트에 있는 설명서가 있고, 완성을 위해, 이 GitHub 이슈에 유의하십시오.

describe('Component TEST', () => {
  ...
  let mockToolBarService: TopToolBarService;
  ...
  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ UsersListComponent ],
      schemas:[ CUSTOM_ELEMENTS_SCHEMA ]
    });
    mockTopToolBarService = TestBed.inject(TopToolBarService);
    spyOn(mockTopToolBarService, 'getCustomer').and.returnValue(of([]));
  }));
  ...

코드를 실행하기 전에 테스트 모듈을 구성해야 한다.그것은 당신의 첩보물체를 넘겨주지 않는 한 알 수 없다.TestBed.configureTestingModule수입으로

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

구성할 모든 보일러 플레이트를 피하기 위해 ng-mock의 사용을 고려할 수 있다.TestBed.

beforeEach(() => MockBuilder(UsersListComponent)
  .mock(TopToolBarService, {
    // adding custom behavior to the service
    getCustomer: jasmine.createSpy().and.returnValue('king'),
  })
);

it('should return data from service function', () => {
  const fixture = MockRender(UsersListComponent);
  // now right after the render the property should be true
  expect(fixtur.point.componentInstance.bDefine).toBe(true);
}));

참조URL: https://stackoverflow.com/questions/58331328/how-to-mock-service-function-in-angular-component-for-unit-test

반응형