반응형
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
에서 변경을 주장하기 전에fetch
es, 테스트를 통해 이 테스트에 필요한 것은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
반응형
'source' 카테고리의 다른 글
Vuex - 변환 유형에 대한 상수이지만 작업 및 Getter에는 해당되지 않습니까? (0) | 2022.08.21 |
---|---|
단일 페이지 vue js 컴포넌트의 UML 클래스 다이어그램을 작성하려면 어떻게 해야 합니까? (0) | 2022.08.21 |
긴 vsInter C/C++ - 포인트 (0) | 2022.08.21 |
고유별 Vue JS v-for 필터 (0) | 2022.08.21 |
상위 컴포넌트와 하위 컴포넌트 간의 Vue.js 동적 양방향 데이터 바인딩 (0) | 2022.08.21 |