如何用Jest在构件测试中模拟服务功能

3hvapo4f  于 2022-12-08  发布在  Jest
关注(0)|答案(3)|浏览(193)

我很难用杰斯特测试Angular 组件。
我有这个组件:

  • 媒体图像.组件.ts*
import { Component, Input } from '@angular/core'
import { SanityService } from '@services/sanity/sanity.service'
import Waypoint from '@interfaces/waypoint'

@Component({
  selector: 'app-media-image',
  templateUrl: './media-image.component.html',
  styleUrls: ['./media-image.component.scss']
})
export class MediaImageComponent {
  @Input() mediaData: Waypoint = null

  constructor(private _sanity: SanityService) {}

  imageUrl(source: any) {
    return this._sanity.urlFor(source)
  }
}

在模板中调用imageUrl
此组件需要SanityService

  • 健全性.服务.ts*
import { Injectable } from '@angular/core'
import { environment } from '@environments/environment'
import imageUrlBuilder from '@sanity/image-url'
import sanityClient from '@sanity/client'

@Injectable({
  providedIn: 'root'
})
export class SanityService {
  sanityClientCredentials = {
    option: sanityClient({
      projectId: environment.sanity.projectId,
      dataset: environment.sanity.dataset,
      apiVersion: environment.sanity.apiVersion
    })
  }

  urlFor(source: any) {
    return imageUrlBuilder(this.sanityClientCredentials.option).image(source).url()
  }

}

我想模拟服务的urlFor函数,只是为了检查它是否用正确的参数调用。
以下是我的尝试:

import { ComponentFixture, TestBed, waitForAsync } 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'

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [MediaImageComponent],
        providers: [{ provide: SanityService }],
        imports: [IonicModule.forRoot()]
      }).compileComponents()

      fixture = TestBed.createComponent(MediaImageComponent)
      component = fixture.componentInstance
      component.mediaData = waypointImage
      fixture.detectChanges()
    })
  )

  it('should create', () => {
    // First
    jest.mock('../../../services/sanity/sanity.service', () => {
      return {
       urlFor: jest.fn()
      }
    })
   
   // Second
   const mockSanityService = SanityService as jest.Mock<SanityService> // to avoid typescript alerts
   const mockService = jest
      .spyOn(mockSanityService.prototype, 'urlFor')
      .mockImplementation((source) => {return 'test'})
    })

    expect(mockService).toHaveBeenCalled()
    expect(component.imageUrl).toHaveBeenCalled()
    expect(component).toBeTruthy()
  })
})

似乎我的模拟被忽略了.我总是从@sanity/image-url包中得到一个错误,它等待特定的数据.
我做错了什么?我不明白什么?
谢谢你的帮助!

i86rm4rw

i86rm4rw1#

终于找到了实现这一目标的方法,感谢这篇文章:Testing Angular Component using JEST
下面是我的测试:

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()
  })
})

希望对别人有用:)

deyfvvtc

deyfvvtc2#

对于将来的用户:你也可以使用ng-mocks使这个过程更简单。这样你就不必自己模拟每个函数来满足类型约束,但是你可以一次模拟整个服务、组件或指令,并且只模拟实际调用的函数。在这个例子中:

const mockSanityService = MockService(SanityService);
mockSanityService.urlFor = jest.fn() // if you want to be able to do an expect on it

在这里,它似乎并不需要太多的工作,但如果你需要模拟大量的依赖关系,它们也有帮助函数。

uqxowvwt

uqxowvwt3#

我不确定这是否有用,但是当我需要模拟一个服务时,我在Jest测试中做了如下操作:

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

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

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

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

相关问题