[英]Jest test if App renders produces Unable to find an element with the text: Profil
[英]React test unable to find an element mocked with jest
我正在嘗試模擬一個反應 select 組件,以便在測試觸發事件中使用它。 下面是我使用 jest 創建的反應 select。
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
的控制台在控制台中打印undefined 。 下面是我測試的火災事件模型:
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
為什么在火災事件發生時該選項沒有更新?
mocking 從庫中默認導出的結構是:
jest.mock("react-select", () => {
return {
__esModule: true,
default: ({ options, onChange }) => {
// Your mock implementation goes here
},
};
})
__esModule: true
很重要
主要的 function 需要返回一個 object ,其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>
);
},
};
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.