codememo

리액트 테스트 라이브러리에서 버튼이 비활성화되었는지 확인합니다.

tipmemo 2023. 4. 3. 21:31
반응형

리액트 테스트 라이브러리에서 버튼이 비활성화되었는지 확인합니다.

React 컴포넌트가 있으며, 이 컴포넌트에는 버튼이 포함되어 있습니다.<span>다음과 같은 요소:

function Click(props) {
    return (
        <button disable={props.disable}>
            <span>Click me</span>
        </button>
    );
}

이 컴포넌트의 로직을 테스트하고 싶다.react-testing-library그리고.mocha+chai.

그 순간 내가 고수했던 문제는getByText("Click me")Selector는<span>DOM 노드, 하지만 테스트를 위해disable의 속성<button>노드. 이러한 테스트 케이스를 처리하기 위한 베스트 프랙티스는 무엇입니까?몇 가지 해결 방법이 있는데, 모두 좀 이상한 것 같습니다.

  1. 사용하다data-test-id위해서<button>요소
  2. 의 상위 항목 중 하나를 선택합니다.<Click />컴포넌트를 선택하고 버튼을 선택합니다.within(...)이 범위
  3. 선택한 요소를 클릭합니다.fireEvent아무 일도 없었는지 확인하세요

좀 더 나은 방법을 제안해 주시겠어요?

버튼이 비활성화되어 있는 경우 아사트

를 사용할 수 있습니다.toHaveAttribute그리고.closest테스트하기 위해서요.

import { render } from '@testing-library/react';

const { getByText } = render(Click);
expect(getByText(/Click me/i).closest('button')).toHaveAttribute('disabled');

또는toBeDisabled

expect(getByText(/Click me/i).closest('button')).toBeDisabled();

단추가 활성화된 경우 아사트

이 버튼이 활성화 되어 있는지 확인하려면not다음과 같이

expect(getByText(/Click me/i).closest('button')).not.toBeDisabled();

사용할 수 있습니다.toBeDisabled()부터@testing-library/jest-domDOM 의 상태를 테스트하는 것은, 커스텀 재스트 매처입니다.

https://github.com/testing-library/jest-dom

예:

<button>Submit</button>
expect(getByText(/submit/i)).toBeDisabled()

버튼이 비활성화되지 않은 테스트를 찾고 있는 사용자용.

import { render } from '@testing-library/react';

const { getByText } = render(Click);
expect(getByText(/Click me/i).getAttribute("disabled")).toBe(null)

리액션 테스트 라이브러리는 권장하지 않는 구현 세부사항을 테스트하고 있다고 정중하게 주장하고 싶습니다.

테스트 결과가 소프트웨어 사용 방법과 비슷할수록 더 많은 자신감을 얻을 수 있습니다.

버튼이 비활성화되어 있으면 사용자는 비활성화 소품을 볼 수 없습니다.대신 아무 일도 일어나지 않습니다.버튼이 활성화 되어 있는 경우, 사용자는 비활성화된 소품 누락이 표시되지 않고, 대신 무언가가 발생하는 것을 볼 수 있습니다.

대신 이 테스트를 해야 한다고 생각합니다.

const Button = (props) => (
  <button 
    type="submit" 
    onClick={props.onClick} 
    disabled={props.disabled}
  >
    Click me
  </button>
);

describe('Button', () => {
  it('will call onClick when enabled', () => {
    const onClick = jest.fn();
    render(<Button onClick={onClick} disabled={false} />);
    userEvent.click(getByRole('button', /click me/i));
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it('will not call onClick when disabled', () => {
    const onClick = jest.fn();
    render(<Button onClick={onClick} disabled={true} />);
    userEvent.click(getByRole('button', /click me/i));
    expect(onClick).not.toHaveBeenCalled();
  });
})

toHaveAttribute는 Atribute를 사용할 때 좋은 옵션입니다.

<button data-testid="ok-button" type="submit" disabled>ok</button>

const button = getByTestId('ok-button')
//const button = getByRole('button');

expect(button).toHaveAttribute('disabled')
expect(button).toHaveAttribute('type', 'submit')
expect(button).not.toHaveAttribute('type', 'button')

expect(button).toHaveAttribute('type', expect.stringContaining('sub'))
expect(button).toHaveAttribute('type', expect.not.stringContaining('but'))

이것이 도움이 되기를 바랍니다.

버튼의 비활성화 프로펠을 테스트하려면@testing-library/react다음과 같이 합니다.

예:

   import { render } from '@testing-library/react';

   const {getByText} = render(<Click/>)

   expect(getByText('Click me').closest('button').disabled).toBeTruthy()

이 문제를 해결하는 또 다른 방법은 역할을 잡고 내부를 확인하는 것입니다.HTML 같은 것,

const { getByRole } = render(<Click />)
const button = getByRole('button')

// will make sure the 'Click me' text is in there somewhere
expect(button.innerHTML).toMatch(/Click me/))

이 방법은 특정 사례에 가장 적합한 솔루션은 아니지만, 실제 버튼이 아닌 버튼 컴포넌트를 처리해야 할 경우 등에 사용할 수 있습니다.

<div role="button"><span>Click Me</span></div>

제 해결책은, 이 케이스가 필요한 것을 충분히 커버하고 있는 것 같습니다.버튼이 비활성화되어 있는지 확인하여 ToHaveBeenCalledTimes는 0을 수신해야 합니다.

 test('Will not call onClick when disabled', () => {
        const mockHandler = jest.fn()

        render(<Button title="Disabled account" disabled={true} onClick={mockHandler} />)
        const button = screen.getByText("Disabled account")
        fireEvent.click(button)

        expect(mockHandler).toHaveBeenCalledTimes(0)
        expect(button).toHaveProperty('disabled', true)
    })

언급URL : https://stackoverflow.com/questions/56593840/check-that-button-is-disabled-in-react-testing-library

반응형