Created
May 28, 2020 07:58
-
-
Save SebinLee/726537f239c495801d5e6446880a4fb8 to your computer and use it in GitHub Desktop.
React Testing Recipe 번역 - Event
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 Toggle from "./toggle"; | |
let container = null; | |
// 가독성을 위해 beforeEach, afterEach는 생략합니다. | |
// 생략된 코드는 위의 Setup/Teardown 부분에 있는 예시코드와 동일합니다. | |
// 생략된 부분을 제대로 입력해야 이벤트가 정상적으로 작동합니다. | |
it("changes value when clicked", () => { | |
const onChange = jest.fn(); | |
act(() => { | |
render(<Toggle onChange={onChange} />, container); | |
}); | |
// 버튼 요소를 선택한 후, 클릭을 발생시킵니다. | |
const button = document.querySelector("[data-testid=toggle]"); | |
expect(button.innerHTML).toBe("Turn on"); | |
act(() => { | |
button.dispatchEvent(new MouseEvent("click", { bubbles: true })); | |
}); | |
expect(onChange).toHaveBeenCalledTimes(1); | |
expect(button.innerHTML).toBe("Turn off"); | |
act(() => { | |
for (let i = 0; i < 5; i++) { | |
button.dispatchEvent(new MouseEvent("click", { bubbles: true })); | |
} | |
}); | |
expect(onChange).toHaveBeenCalledTimes(6); | |
expect(button.innerHTML).toBe("Turn on"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment