我正在尝试模拟一个反应选择组件,以便在测试触发事件中使用它。以下是我使用笑话创建的反应选择。
jest.mock("react-select", () => ({ options, onChange }) => {
function handleChange(event) {
const option = [];
option.push(options.find(option => option === event.currentTarget.value));
onChange(option);
console.log(option);............................................................//line 1
}
return (
<select
data-testid="test-select"
name="users"
label="users"
options={[
"a",
"b",
"c",
"d",
"e"
]}
onChange={handleChange}
>
{options.map(value => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
);
});
问题是line 1
上的控制台在控制台中打印未定义。以下是我的测试的火灾事件模型:
const chooseInput = getByTestId("test-select");
fireEvent.change(chooseInput, {
target: {
value: "b"
}
});
测试失败,因为:
expect(received).toBeInTheDocument()
received value must be an HTMLElement or an SVGElement.
Received has value: null
为什么在火灾事件开始时未更新该选项?
答案 0 :(得分:0)
从库中模拟默认导出的结构为:
jest.mock("react-select", () => {
return {
__esModule: true,
default: ({ options, onChange }) => {
// Your mock implementation goes here
},
};
})
__esModule: true
很重要
main函数需要返回一个具有default
属性的对象,该对象表示您的模拟实现
因此完整的代码应该是
jest.mock("react-select", () => {
return {
__esModule: true,
default: ({
options,
onChange
}) => {
function handleChange(event) {
const option = [];
option.push(options.find(option => option === event.currentTarget.value));
onChange(option);
console.log(option);
}
return ( <
select data - testid = "test-select"
name = "users"
label = "users"
options = {
[
"a",
"b",
"c",
"d",
"e"
]
}
onChange = {
handleChange
} > {
options.map(value => ( <
option key = {
value
}
value = {
value
} > {
value
} <
/option>
))
} <
/select>
);
},
};
})