Created
May 28, 2020 07:54
-
-
Save SebinLee/b3dedbb073e7ed7172dd0aed684eae6c to your computer and use it in GitHub Desktop.
React Testing Recipe 번역 - Data Fetching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { render, unmountComponentAtNode } from "react-dom"; | |
import { act } from "react-dom/test-utils"; | |
import User from "./user"; | |
let container = null; | |
// 가독성을 위해 beforeEach, afterEach는 생략합니다. | |
// 생략된 코드는 위의 Setup/Teardown 부분에 있는 예시코드와 동일합니다. | |
it("renders user data", async () => { | |
//가짜 데이터를 생성합니다. | |
const fakeUser = { | |
name: "Joni Baez", | |
age: "32", | |
address: "123, Charming Avenue" | |
}; | |
//Jest.spyOn을 이용해 fetch의 호출 값을 가짜 데이터로 대체합니다. | |
jest.spyOn(global, "fetch").mockImplementation(() => | |
Promise.resolve({ | |
json: () => Promise.resolve(fakeUser) | |
}) | |
); | |
// Resolved 프로미스를 적용하기 위해 비동기 버전의 act를 사용합니다. | |
await act(async () => { | |
render(<User id="123" />, container); | |
}); | |
expect(container.querySelector("summary").textContent).toBe(fakeUser.name); | |
expect(container.querySelector("strong").textContent).toBe(fakeUser.age); | |
expect(container.textContent).toContain(fakeUser.address); | |
// 테스트가 완벽히 독립될 수 있도록 가짜 데이터를 삭제합니다. | |
global.fetch.mockRestore(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment