简体   繁体   English

如何使用 rxjs 下一个方法为服务文件编写单元测试用例

[英]How write unit test cases for service file with rxjs next method

I am new to angular unit testing and I have tried to write test cases for service file.我是 angular 单元测试的新手,我曾尝试为服务文件编写测试用例。 I need to write test cases for below code我需要为下面的代码编写测试用例

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class EmployeeDetailsService {
  private readonly employeeRoles = new BehaviorSubject<any>([]);
  private readonly isEmployeeData = new BehaviorSubject<boolean>(true);

  employeeRolesData = this.employeeRoles.asObservable();
  isEmployee = this.isEmployeeData.asObservable();

  addEmployeeRoles(data: string) {
    this.employeeRoles.next(data);
  }

  checkIsEmployee(data: boolean) {
    this.isEmployeeData.next(data);
  }
}

what I have tried is我试过的是

import { TestBed } from '@angular/core/testing';
import { EmployeeDetailsService } from './EmployeeDetails.service';

describe('EmployeeDetailsService', () => {
    let service: EmployeeDetailsService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(EmployeeDetailsService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });

    it('addEmployeeRoles', () => {
        service.addEmployeeRoles.subscribe(data => {
            expect(data).toEqual(data);
        })
    });

    it('checkIsEmployee', () => {
        service.checkIsEmployee.subscribe(data=>{
            expect(data).toEqual(data)
        })
    });

})

Unit test cases are passing, but code coverage is not improving.单元测试用例通过了,但代码覆盖率没有提高。 So please help me to solve this.所以请帮我解决这个问题。

The problem arise when you use expect in a subscribe .当您在subscribe中使用expect时会出现问题。 Since it's asynchronous, the expect can be executed after your test.由于它是异步的,因此可以在您的测试之后执行expect

One of the way to solve this problem is to add a fuction that will be called inside the subscribe to notify Karma that your test is done like this:解决此问题的方法之一是添加一个函数,该函数将在subscribe内部调用,以通知 Karma 您的测试已完成,如下所示:

it('checkIsEmployee', (done) => {
    service.checkIsEmployee.subscribe(data=>{
        expect(data).toEqual(data);
        done();
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM