.... TS configuration$ : Observable = this.configSe" /> .... TS configuration$ : Observable = this.configSe" /> .... TS configuration$ : Observable = this.configSe"/>

Unit tests for Angular observable to modify observable return value for different test cases

21 Views Asked by At

HTML

<ng-container *ngIf="configuration$ | async as configuration">
....
</ng-container>

TS

configuration$ :  Observable<Configuration> = this.configService.configuration$;

configService.sevice.ts

private _configuration: Observable<Configuration> = this.service.loadDetails();

get configuration(): Observable<Configuration>{
return this._configuration;
}

This setup runs an api service call and fetch some configuration details from backend. let's say

{
employee_name: "SHubham",
employee_dependents: [
{name: "abc",include: true},
{name: "xyz",include: true},
{name: "ert",include: true},
]}

Now, I am trying to write test cases to check if the dependent details should be included or not for a particular employee.

How can I use mock services to validate for 2 conditions:

  1. if all the dependents include are true
  2. if all the dependents include are false/

since these data are sent from backend, how can I modify the response of api and write unit tests for them?

1

There are 1 best solutions below

0
AliF50 On

Here is how you can mock services in a component: https://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services

You can also use just an object for the mock, something like this: https://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services

For you, it could be:

// make a mock config service to be provided later
let mockConfigService: any;
// make a behavior subject that will be configuration
const DEFAULT_CONFIGURATION = { employee_name: "abc", employee_dependents: [] };
const mockConfiguration = new BehaviorSubject<Configuration>(DEFAULT_CONFIGURATION);

beforeEach(() => {
  // make mock service have configuration property assigned to
  // mock configuration behavior subject
  mockConfigService = { configuration: mockConfiguration.asObservable() };
  ...

  TestBed.configureTestingModule({
    // Provide a mock for the real Config service
    providers: [{ provide: ConfigService, useValue: mockConfigService }]
  });
});

// Reset the observable after each test
afterEach(() => {
  mockConfiguration.next(DEFAULT_CONFIGURATION);
});

it('has dependents test case', () => {
  mockConfiguration.next({
   employee_name: "SHubham",
   employee_dependents: [
   {name: "abc",include: true},
   {name: "xyz",include: true},
   {name: "ert",include: true},
  ]});
  ...
});

it('no dependents test case', () => {
   mockConfiguration.next(DEFAULT_CONFIGURATION);
});