jor*_*gen 5 javascript unit-testing reactjs react-testing-library
我正在尝试测试组件是否由于输入元素的变化而更新。我使用fireEvent.change()-function,然后如果我检查使用getByPlaceholderText它发现的节点的值已按预期进行了更新。但是我看不到react组件本身的变化。
这可能是因为更改直到重新渲染才发生。我将如何测试呢?react-testing-library rerender似乎是“从头开始”启动组件(即没有新的输入值),却waitForElement从不找到它在等待什么。
这是组件TestForm.js:
import React from 'react';
import { withState } from 'recompose';
const initialInputValue = 'initialInputValue';
const TestForm = ({ inputValue, setInputValue }) => (
<>
{console.log('inputValue', inputValue)}
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="placeholder" />
{inputValue !== initialInputValue && <div>Input has changed</div>}
</>
);
export default withState('inputValue', 'setInputValue', initialInputValue)(TestForm);
Run Code Online (Sandbox Code Playgroud)
这是测试,使用npx jest test.js以下命令运行:
import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';
import TestForm from './TestForm';
afterEach(cleanup);
describe('TestForm', () => {
it('Change input', async () => {
const { getByPlaceholderText, getByText } = render(<TestForm />);
const inputNode = getByPlaceholderText('placeholder');
fireEvent.change(inputNode, { target: { value: 'new value' } });
console.log('inputNode.value', inputNode.value);
await waitForElement(() => getByText('Input has changed'));
});
});
Run Code Online (Sandbox Code Playgroud)
sam*_*war 10
使用用户事件库
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
afterEach(cleanup);
test("form", async () => {
const user = userEvent.setup();
const { getByPlaceholderText, getByText } = render(<TestForm />);
await user.type(getByPlaceholderText("placeholder"), "new value");
await waitFor(() => {
expect(getByText("Input has changed")).toBeInTheDocument();
});
});
Run Code Online (Sandbox Code Playgroud)
该代码对我有用:
import React from "react";
const initialInputValue = "initialInputValue";
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = { inputValue: initialInputValue };
}
render() {
const { inputValue } = this.state;
return (
<div>
{console.log("inputValue", inputValue)}
<input
value={inputValue}
onChange={e => this.setState({ inputValue: e.target.value })}
placeholder="placeholder"
/>
{inputValue !== initialInputValue && <div>Input has changed</div>}
</div>
);
}
}
import { render, cleanup, fireEvent } from "react-testing-library";
import "jest-dom/extend-expect";
afterEach(cleanup);
test("form", () => {
const { getByPlaceholderText, getByText } = render(<TestForm />);
fireEvent.change(getByPlaceholderText("placeholder"), {
target: { value: "new value" }
});
expect(getByText("Input has changed")).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
但是它在codeandbox中不起作用,我想他们在保持浏览器和测试环境分离方面存在一些问题。
| 归档时间: |
|
| 查看次数: |
3613 次 |
| 最近记录: |