'How to inject a mock service in an Angular component tested by Jest

I've used Jasmine+Karma in the past to test my Angular component. We are starting a big project and I think it's better we use Jest because it will allow to run in parallel all of our tests (because it will be a project developed over several years and a lot of tests are expected).

So now, I've a typical usecase: I've an Angular component that has a dependency on a service (which basically retrieves data from some HTTP calls), and when an action happens (or just at the initialization) I want to ensure the service method has been called and return some mock data.

With Jasmine, I would do something like:

beforeEach(() => {
  testQuote = 'Test Quote';

  const twainService = jasmine.createSpyObj('TwainService', ['getQuote']);
  getQuoteSpy = twainService.getQuote.and.returnValue(of(testQuote));

  TestBed.configureTestingModule({
    declarations: [TwainComponent],
    providers: [{provide: TwainService, useValue: twainService}]
  });

  fixture = TestBed.createComponent(TwainComponent);
  component = fixture.componentInstance;
  quoteEl = fixture.nativeElement.querySelector('.twain');
});

it('should show quote after component initialized', () => {
  fixture.detectChanges();  // onInit()

  // sync spy result shows testQuote immediately after init
  expect(quoteEl.textContent).toBe(testQuote);
  expect(getQuoteSpy.calls.any())
    .withContext('getQuote called')
    .toBe(true);
});

What would be the equivalent of this with Jest? I did search quite a bit, but I find either examples that are not applicable to Angular, or do not apply to a service injected.

(I set up Jest following this, if it helps: https://dev.to/alfredoperez/angular-10-setting-up-jest-2m0l)



Solution 1:[1]

you need to create a mock file which contains all the mock responses that you want to store. For Example this is the response:

export class TestListMockValues { TestData = { status: true, result: { data: [], }, }; TestResp = { status: true, result: { data: { url: 'dummy_url', }, }, };

}

then under the spec file where you have get the mock value you can easily initialize the object and use it For Example

let testListGetMockValues = new TestListMockValues();

then you can use object and get valus sore them 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hamza Farrukh