dom-testing-library 또는 react-testing-library에서 입력값을 테스트하는 최선의 방법
「 」의 값을 입니까?<input>를 나타내다dom-testing-library/react-testing-library
는, 「Raw Input(로우 입력)」을 입니다.closest()method를 그 、 을 、 the 、 접 、 접 、 접 、 접 the the the the the 에 직접 액세스 할 수 .value★★★★
const input = getByLabelText("Some Label")
expect(input.closest("input").value).toEqual("Some Value")
HTML 속성에 직접 접속하지 않아도 되는 방법이 있으면 좋겠다고 생각했습니다.그것은 시험 도서관 정신으로 보이지 않았다.아마도 joke-dom to HaveTextContent matcher와 같은 것:
const input = getByLabelText("Some Label")
expect(input).toHaveTextContent("Some Value")
갱신하다
코멘트의 의뢰에 근거해, 입력란에 값을 테스트할 필요성을 느낀 상황을 나타내는 코드 예를 소개합니다.
이것은 제가 앱에 구축한 모달 컴포넌트를 단순화한 버전입니다.아주 단순하죠여기서의 전체 개념은 문자열 받침에 따라 텍스트가 미리 채워진 입력으로 모달(modal)이 열린다는 것입니다.사용자는 이 입력을 자유롭게 편집하여 버튼을 눌러 제출할 수 있습니다.단, 사용자가 모달 닫았다가 다시 열었을 경우에는 원래 문자열 받침대로 텍스트를 리셋하고 싶습니다.이전 버전의 모달은 입력값을 리셋하지 않았기 때문에 테스트를 작성했습니다.
각 소품 유형이 명확하도록 TypeScript로 작성했습니다.
interface Props {
onClose: () => void
isOpen: boolean
initialValue: string
}
export default function MyModal({ onClose, isOpen, initialValue }) {
const [inputValue, setInputValue] = useState(initialValue)
// useEffect does the reset!
useEffect(() => {
if (!isOpen) {
setNameInput(initialValue)
}
}, [isOpen, initialValue])
return (
<SomeExternalLibraryModal isOpen={isOpen} onClose={onClose}>
<form>
<input
value={inputValue}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setInputValue(e.target.value)
}
/>
<button onClick={onClose}>Cancel</button>
</form>
</SomeExternalLibraryModal>
)
}
이 테스트 라이브러리의 테스트 방법에 대해 의심하는 것은 옳은 일입니다. 가장 은 '우리'를 입니다.getByDisplayValue됩니다.textarea또는 찾으려는 값이 있는 것을 선택합니다.를 들어로 들 수 있습니다.를 들어, 「 」가 「 」, 「 」, 「 」, 「 」, 「 」를 ,inputValue = 'test'
expect(screen.getByDisplayValue('test')).toBeInTheDocument();
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ '만들기'를 입니다.MyModal이 여러.입력이 여러 개라도 테스트 철학은 중요하지 않습니다.★★★★★★만 있으면,getByDisplayValue이 값을 가진 입력을 찾으면 테스트는 성공합니다.입력이 여러 개 있고 정확한 입력에 값이 있는지 테스트하려면 요소를 조사하여 올바른 입력인지 확인할 수 있습니다.
": " " 가 합니다.jest-dom이게 먹혀들게.
expect(screen.getByDisplayValue('test')).toHaveAttribute('id', 'the-id');
또는 (없음)jest-dom):
expect(screen.getByDisplayValue('test').id).toBe('the-id');
물론 원하는 속성을 검색할 수 있습니다.
값을 테스트하기 위한 마지막 대안은 역할별로 입력을 찾는 것입니다.이 예에서는 라벨을 추가하고 를 통해 입력에 관련짓지 않으면 작동하지 않습니다.htmlFor기여하다.그런 다음 다음과 같이 테스트할 수 있습니다.
expect(screen.getByRole('input', { name: 'the-inputs-id' })).toHaveValue('test');
또는 (없음)jest-dom):
expect(screen.getByRole('input', { name: 'the-inputs-id' }).value).toBe('test');
이 방법은 올바른 입력에 값이 있는지 확인하면서 값을 테스트하는 가장 좋은 방법이라고 생각합니다.제안하고 싶은 것은getByRole이 경우에도 예제에 라벨을 추가해야 합니다.
를 사용하여 표시된 값이 포함된 입력 요소를 가져와 요소와 비교할 수 있습니다.
type TestElement = Document | Element | Window | Node
function hasInputValue(e: TestElement, inputValue: string) {
return screen.getByDisplayValue(inputValue) === e
}
테스트 시:
const input = screen.getByLabelText("Some Label")
fireEvent.change(input, { target: { value: '123' } })
expect(hasInputValue(input, "123")).toBe(true)
expect(screen.getByLabelText("Name")).toHaveValue("hello");- 입력값을 가져옵니다. : )
<label class="label" for="name">
Name
</label>
<div class="control ">
<input
class="input"
for="name"
id="name"
name="name"
value="hello"
/>
</div>
테스트:
userEvent.type(screen.getByLabelText("Name"), "hello")
await waitFor(() => {
expect(screen.getByLabelText("Name")).toHaveValue("hello");
});
사용.@testing-library/dom(또는 여기에 있는 랩된 라이브러리 중 하나)
다음 작업을 수행할 수 있습니다.
expect(inputField).toHaveDisplayValue('some input value');
완전한 예:
test('should show input with initial value set', async () => {
render(<Input type="text" value="John Doe" data-testid="form-field-firstname" />);
const inputField = await screen.findByTestId(`form-field-firstname`);
await waitFor(() => expect(inputField).toHaveDisplayValue('John Doe')));
});
테스트 라이브러리를 사용하여 테스트할 수 있는 매우 깨끗한 방법이 있습니다.
//In describe
const renderComponent = (searchInputValue, handleSearchInputValue) => {
const wrapper = render(<yourComponentWithInput
value={searchInputValue}
onChange={handleSearchInputValue}
/>);
return wrapper;
};
//In test
const mockHandleSearchInputValue = jest.fn();
const { getByLabelText } = renderComponent('g', mockHandleSearchInputValue);
const inputNode = getByLabelText('Search label'); // your input label
expect(inputNode.value).toBe('s'); // to test input value
fireEvent.change(inputNode, { target: { value: 'su' } }); // triggers onChange event
expect(mockHandleSearchInputValue).toBeCalledWith('su'); // tests if onChange handler is called with proper value
언급URL : https://stackoverflow.com/questions/62473970/best-way-to-test-input-value-in-dom-testing-library-or-react-testing-library
'programing' 카테고리의 다른 글
| 리액트를 사용하여 html 엔티티를 표시하는 방법 (0) | 2023.04.05 |
|---|---|
| 각도 js 애플리케이션을 위해 투영기에서 애니메이션을 비활성화하는 방법 (0) | 2023.04.05 |
| 네트워크에서 오류 StrictMode$AndroidBlockGuardPolicy.onNetwork (0) | 2023.04.05 |
| JSON 개체를 포맷할 때 '{'와 '['의 차이 (0) | 2023.04.05 |
| JQuery를 사용하여 AJAX를 사용하여 Excel 데이터 전송 (0) | 2023.04.05 |