source

VueJS / Jest : 여러 가져오기 응답을 조롱합니다.

goodcode 2022. 8. 21. 14:10
반응형

VueJS / Jest : 여러 가져오기 응답을 조롱합니다.

2개의 컴포넌트에 의존하는 매우 간단한 컴포넌트가 있습니다.fetch콜:

<template>
  <div>
    <div ng-if="this.foo">
      {{ foo.name }}
    </div>
    <div ng-if="this.bar">
      {{ bar.address }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'identity-card',
  data() {
    return {
      foo:undefined,
      bar:undefined
    }
  }
  created() {
    Promise.all([
      fetch('http://ul/to/api/foo'),
      fetch('http://ul/to/api/bar')
    ]).then(async (response) => {
      this.foo = await response[0].json();
      this.bar = await response[1].json();
    })
  }
}
</script>

그 컴포넌트를 테스트하려고 합니다.Jest내가 조롱하는 법을 찾은 동안Promise와 함께Jest둘 다 조롱할 방법이 없었어요fetch응답합니다.

외부 lib를 추가하지 않고 코드를 수정하지 않고 어떻게 하면 좋을까요?

설정할 수 있습니다.global.fetch에 대해서jest.fn()각 예상에 대해 API를 사용합니다.fetch호출:

const makeFetchResp = value => ({ json: async() => value })   // mock fetch().json()
const mockFetch = jest.fn()
                   .mockReturnValueOnce(makeFetchResp(true))  // 1st fetch() returns true
                   .mockReturnValueOnce(makeFetchResp(false)) // 2nd fetch() returns false
global.fetch = mockFetch

에서 변경을 주장하기 전에fetches, 테스트를 통해 이 테스트에 필요한 것은Promise를 위한then호출되는 콜백이 조작은, 다음과 같이 실행할 수 있습니다.

const flushPromises = () => new Promise(r => setTimeout(r))
await flushPromises()

테스트 결과는 다음과 같습니다.

it('fetches foo bar', async () => {
  const makeFetchResponse = value => ({ json: async() => value })
  const mockFetch = jest.fn()
    .mockReturnValueOnce(makeFetchResponse(true))
    .mockReturnValueOnce(makeFetchResponse(false))
  global.fetch = mockFetch

  const wrapper = shallowMount(MyComponent)

  await flushPromises()

  expect(mockFetch).toHaveBeenCalledTimes(2)
  expect(wrapper.vm.foo).toBeTruthy()
  expect(wrapper.vm.bar).toBeFalsy()
})

언급URL : https://stackoverflow.com/questions/65837171/vuejs-jest-mocking-multiple-fetch-responses

반응형