Migrate Jasmine tests to Jest in Angular 16 application

287 Views Asked by At

We have a big NX Workspace with different Angular 16 projects (each is a MFE with module federation).

We want to migrate the tests from Karma/Jamsine to Jest to improve performance. However, while the expect APIs are similar, the whole mocking concept seems quite different and I cannot find a good guide to migrate Jasmine spies/mocks into Jest ones.

A test example in Jasmine:

import { OrderDetailsComponent } from './order-details.component';
import { ActivitiesByTrackingNumber, ActivityDocument, ActivityMock, ActivityService, BlobService } from '@services';

import SpyObj = jasmine.SpyObj;              // <---
import createSpyObj = jasmine.createSpyObj;  // <---

describe('OrderDetailsComponent', () => {
  let component: OrderDetailsComponent;

  let activityServiceSpy: SpyObj<ActivityService>;  // <---
  let blobServiceSpy: SpyObj<BlobService>;          // <---

  beforeEach(async () => {
    blobServiceSpy = createSpyObj('BlobService', ['openBlobInNewWindow']); // <---
    activityServiceSpy = createSpyObj('ActivityService', [ // <---
         'getActivities', 
         'getChildActivities', 
         'getDocumentContent']);

    // We pass the Jasmine spies to the component constructor
    component = new OrderDetailsComponent(activityServiceSpy, blobServiceSpy);

    activityServiceSpy.getChildActivities.and.returnValue(
      of(ActivityMock.getChildActivities())
    );
    activityServiceSpy.childActivitiesSubject$ = new BehaviorSubject(ActivityMock.getChildActivities());
  });

  it('should call getChildActivities when submittedImeiSubject$ emits', () => {
    spyOn(component, 'getChildActivities');
    component.ngOnInit();
    expect(component.orderDetail).toBeDefined();
    expect(component.getChildActivities).toHaveBeenCalled();
  });
  // ...
 });

And here how I am trying to migrate to Jest:

describe('OrderDetailsComponent', () => {
  let component: OrderDetailsComponent;

  // let activityServiceSpy2 = jest.mock('ActivityService'); // This also does not work
 
  let activityServiceSpy = {
    getActivities: jest.fn(),
    getChildActivities:  jest.fn(),
    getDocumentContent: jest.fn(),
    childActivitiesSubject$: new BehaviorSubject(ActivityMock.getChildActivities())
  };

  let blobServiceSpy = {
    openBlobInNewWindow: jest.fn()
  };

  beforeEach(async () => {

    // activityServiceSpy is not accepted as the correct type (ActivityService)
    component = new OrderDetailsComponent(activityServiceSpy, blobServiceSpy);

   activityServiceSpy.getChildActivities
                     .mockReturnValue(of(ActivityMock.getChildActivities()));

// ...
});

What is the right process to translate jasmine spy objects into the Jest context?

0

There are 0 best solutions below