Jest에서 버튼 클릭 시뮬레이션
버튼 클릭 시뮬레이션은 매우 쉽고 표준적인 조작처럼 보입니다.하지만 Jest.js 테스트에서는 작동하지 않습니다.
jQuery를 사용하여 시도했지만 아무것도 트리거되지 않았습니다.
import { mount } from 'enzyme';
page = <MyCoolPage />;
pageMounted = mount(page);
const button = pageMounted.find('#some_button');
expect(button.length).toBe(1); // It finds it alright
button.simulate('click'); // Nothing happens
#1 Jest 사용
Jest 모의 콜백 함수를 사용하여 클릭 이벤트를 테스트하는 방법은 다음과 같습니다.
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test Button component', () => {
it('Test click event', () => {
const mockCallBack = jest.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
효소라는 모듈도 사용하고 있습니다.효소는 반응 성분을 더 쉽게 주장하고 선택할 수 있도록 해주는 테스트 유틸리티입니다.
#2 Sinon 사용
또한 자바스크립트용 독립형 테스트 스파이, 스터브 및 모크인 Sinon이라는 다른 모듈을 사용할 수 있습니다.다음과 같이 표시됩니다.
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Button from './Button';
describe('Test Button component', () => {
it('simulates click events', () => {
const mockCallBack = sinon.spy();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack).toHaveProperty('callCount', 1);
});
});
#3 스파이 사용
마지막으로 자신만의 순진한 스파이를 만들 수 있습니다(정당한 이유가 없는 한 이 접근방식은 권장하지 않습니다).
function MySpy() {
this.calls = 0;
}
MySpy.prototype.fn = function () {
return () => this.calls++;
}
it('Test Button component', () => {
const mySpy = new MySpy();
const mockCallBack = mySpy.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mySpy.calls).toEqual(1);
});
승인된 답변의 솔루션은 권장되지 않습니다.
#4 소품에 직접 전화하기
효소 시뮬레이션은 버전 4에서 제거되어야 합니다.메인 메인 메인 메인터넌스는 내부적으로 시뮬레이션을 하는 프롭 함수를 직접 호출할 것을 제안하고 있습니다.한 가지 솔루션은 이러한 소품을 호출하는 것이 올바른지 직접 테스트하는 것입니다.또는 인스턴스 메서드를 시뮬레이션하여 프로펠러 함수가 호출하는 것을 테스트하고 유닛을 테스트합니다.
예를 들어 클릭을 호출할 수 있습니다.
wrapper.find('Button').prop('onClick')()
또는
wrapper.find('Button').props().onClick()
폐지 정보:.simulate() #2173의 폐지
Jest를 사용하면 다음과 같이 할 수 있습니다.
test('it calls start logout on button click', () => {
const mockLogout = jest.fn();
const wrapper = shallow(<Component startLogout={mockLogout}/>);
wrapper.find('button').at(0).simulate('click');
expect(mockLogout).toHaveBeenCalled();
});
테스트 라이브러리에서는 클릭 기능으로 쉽게 실행할 수 있습니다.
의 일부입니다.user-event
모든 dom 환경(dom, jsdom, 브라우저 등)에서 사용할 수 있는 라이브러리
문서의 예는 다음과 같습니다.
import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
test('click', () => {
render(
<div>
<label htmlFor="checkbox">Check</label>
<input id="checkbox" type="checkbox" />
</div>,
)
userEvent.click(screen.getByText('Check'))
expect(screen.getByLabelText('Check')).toBeChecked()
})
다음과 같은 방법으로 클릭 시 기록된 핸들러를 호출할 수 있습니다.
import { shallow } from 'enzyme'; // Mount is not required
page = <MyCoolPage />;
pageMounted = shallow(page);
// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();
형제자매의 코멘트에 제시된 솔루션 외에 테스트 방식을 약간 변경하여 페이지 전체를 한꺼번에 테스트하는 것이 아니라 격리된 컴포넌트 테스트를 실행할 수 있습니다.이것에 의해, 테스트의 심플화를 도모할 수 있습니다.onClick()
및 유사한 이벤트(아래 예 참조).
모든 컴포넌트를 함께 테스트하지 않고 한 번에 하나의 컴포넌트만 테스트하는 것이 아이디어입니다.이 경우 모든 자녀 컴포넌트는 jest.mock() 함수를 사용하여 조롱됩니다.
이 , 하다.onClick()
된 상태로 할 수 .SearchForm
Jest 및 react-test-renderer를 사용한 컴포넌트.
import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';
describe('SearchForm', () => {
it('should fire onSubmit form callback', () => {
// Mock search form parameters.
const searchQuery = 'kittens';
const onSubmit = jest.fn();
// Create test component instance.
const testComponentInstance = renderer.create((
<SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
)).root;
// Try to find submit button inside the form.
const submitButtonInstance = testComponentInstance.findByProps({
type: 'submit',
});
expect(submitButtonInstance).toBeDefined();
// Since we're not going to test the button component itself
// we may just simulate its onClick event manually.
const eventMock = { preventDefault: jest.fn() };
submitButtonInstance.props.onClick(eventMock);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith(searchQuery);
});
});
버튼 컴포넌트를 직접 테스트해야 했습니다.이 테스트들은 나에게 효과가 있다;-)
import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";
describe("Button Component Tests", () => {
it("Renders correctly in DOM", () => {
shallow(
<Button text="Test" />
);
});
it("Expects to find button HTML element in the DOM", () => {
const wrapper = shallow(<Button text="test"/>)
expect(wrapper.find('button')).toHaveLength(1);
});
it("Expects to find button HTML element with className test in the DOM", () => {
const wrapper = shallow(<Button className="test" text="test"/>)
expect(wrapper.find('button.test')).toHaveLength(1);
});
it("Expects to run onClick function when button is pressed in the DOM", () => {
const mockCallBackClick = jest.fn();
const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
wrapper.find('button').simulate('click');
expect(mockCallBackClick.mock.calls.length).toEqual(1);
});
});
import React from "react";
import { shallow } from "enzyme";
import Button from "../component/Button/Button";
describe("Test Button component", () => {
let container = null;
let clickFn = null;
beforeEach(() => {
clickFn = jest.fn();
container = shallow(<Button buttonAction={clickFn} label="send" />);
});
it("button Clicked", () => {
container.find("button").simulate("click");
expect(clickFn).toHaveBeenCalled();
});
});
언급URL : https://stackoverflow.com/questions/43747397/simulate-a-button-click-in-jest
'source' 카테고리의 다른 글
Lodash Debounce는 비난하지 않는다. (0) | 2023.02.14 |
---|---|
AngularJS - 컨트롤러 내부에서 상태를 변경하는 방법 (0) | 2023.02.14 |
PHP에서 서버 시간대 가져오기 (0) | 2023.02.14 |
python을 사용하여 JSON을 구문 분석하는 동안 'module' 개체에 특성 'loads'가 없습니다. (0) | 2023.02.14 |
GCE: 로그인할 수 없습니다. VM 게스트 환경이 오래되어 사용되지 않는 'sshKeys' 메타데이터 항목만 지원합니다. (0) | 2023.02.14 |