【发布时间】:2021-02-14 23:25:05
【问题描述】:
我想测试一个选择更改功能,代码如下:
import React, { useEffect, useState } from 'react';
import Select from 'react-select';
function Component1(props) {
const [content, setContent] = useState('initialized Value');
const [color, setColor] = useState('initialized Value');
const options = [
{ value: 'red', label: 'Red' },
{ value: 'green', label: 'Green' },
{ value: 'blue', label: 'Blue' },
];
useEffect(async () => {
fetchSomeData();
// onclickButton();
}, []);
const fetchSomeData = async () => {
console.log('fetchSomeData');
};
const onclickButton = () => {
console.log('do something here onclickButton');
setContent('updated Value');
};
const resetColor = (value) => {
console.log(value);
setColor(value);
};
return (
<div data-testid='Component1'>
Component1
<button data-testid='button' onClick={onclickButton}>
Button
</button>
<div>Button Test :{content}</div>
<Select aria-label='select-Label' data-testid='select' options={options} value={color} onChange={resetColor} />
<div data-testid='color-value'>Current Color:{color}</div>
</div>
);
}
我做了一些研究,他们说最好的方法是模拟一个选择并测试它:
beforeEach(() => {
render(<Component1 />);
});
test('should 3', () => {
jest.doMock('react-select', () => ({ options, value, onChange }) => {
function handleChange(event) {
const option = options.find((option) => option.value === event.currentTarget.value);
onChange(option);
}
return (
<select data-testid='custom-select' value={value} onChange={handleChange}>
{options.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
);
});
fireEvent.change(screen.getByTestId('select'), {
target: { value: 'green' },
});
test('should 2', () => {
// screen.debug()
const onclickButton = jest.fn();
// render(<Component1 onclickButton={onclickButton} />);
fireEvent.click(screen.getByTestId('button'), {
// target: { value: 'JavaScript' },
});
});
在我运行测试后,我得到了这个:
TestingLibraryElementError: Unable to find an element by: [data-testid="select"]
有人可以帮我吗?我只想下面的代码可以被单元测试覆盖
更新:
我尝试使用 queryByLabelText,它可以工作,但似乎仍然没有触发 onChange 事件。我懂了: 预期元素具有文本内容: 当前颜色:绿色 已收到: 当前颜色:红色
fireEvent.select(screen.queryByLabelText('select-Label'),{target:{value:'green'}})
expect(screen.queryByTestId('color-value')).toHaveTextContent('Current Color:green');
【问题讨论】:
-
在我看来
getByTestId没有被导入。你会确认吗? -
是的,我可以确定
getByTestId已经被导入了,case我有2个测试用例,另外一个也用getByTestId,测试通过了 -
@Jai 我找到了原因——我错过了 getByTestId 函数之前的屏幕。但它仍然给出了一个错误说 —— Unable to find an element by: [data-testid="select"]
标签: reactjs jestjs react-testing-library