angular - How to mock service's function in component's test with Jest - TagMerge
2How to mock service's function in component's test with JestHow to mock service's function in component's test with Jest

How to mock service's function in component's test with Jest

Asked 8 months ago
0
2 answers

I'm not sure it will help, but what I do in my Jest tests when I need to mock a service is the following:

jest.mock('...../myService');

describe('...', () => {
    let myServiceMock: MyService;
    ...

    beforeEach(() => {
        myServiceMock = TestBed.inject(myServiceMock);
        ...

        jest.spyOn(myServiceMock, 'someServiceMethod').mock...
    });
});

Source: link

0

Finally find a way to achieve that, thanks to this post : Testing Angular Component using JEST

Here is my test:

import { ComponentFixture, TestBed } from '@angular/core/testing'
import { IonicModule } from '@ionic/angular'
import { MediaImageComponent } from './media-image.component'
import { SanityService } from '../../../services/sanity/sanity.service'

import { waypointImage } from '../../../mocks/waypoint.mocks'

const mockSanityService = {
  urlFor: jest.fn()
}

describe('MediaImageComponent', () => {
  let component: MediaImageComponent
  let fixture: ComponentFixture<MediaImageComponent>
  let spy
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [MediaImageComponent],
        providers: [{ provide: SanityService, useValue: mockSanityService }],
        imports: [IonicModule.forRoot()]
      }).compileComponents()

      fixture = TestBed.createComponent(MediaImageComponent)
      component = fixture.componentInstance
      component.mediaData = waypointImage
      spy = jest.spyOn(component, 'imageUrl')
      fixture.detectChanges()
    })
  )

  afterEach(() => {
    if (fixture) {
      fixture.destroy()
    }
    mockSanityService.urlFor.mockReset()
    spy.mockClear()
  })

  it('should create', () => {
    mockSanityService.urlFor.mockImplementationOnce(() => 'plop')

    expect(mockSanityService.urlFor).toHaveBeenCalled()
    expect(spy).toHaveBeenCalled()
    expect(component).toBeTruthy()
  })
})

I hope it will be useful for someone else :)

Source: link

Recent Questions on angular

    Programming Languages