如何使用 React 测试库将事件属性传递给 customEvent?
How can I pass event properties to a customEvent using React Testing Library?
我正在尝试使用 RTL 测试组件,该组件使用 customEvent 来触发显示。给定这样的组件:
const Alerts = () => {
const [alerts, setAlerts] = useState([]);
const addAlert = (body, type = 'info', timeout = 7500) => {
const key = nextIndex++;
setAlerts([
...alerts,
{ key, body, type },
]);
// Set a timer to remove the alert.
setTimeout(() => {
setAlerts(alerts.filter((alert) => alert.key !== key));
}, timeout);
};
document.addEventListener(
'newalert',
({ details:
{
body = '',
type = '',
timeout = 1000
} = {}
}) => {
addAlert(body, type, timeout);
});
return (
<>
{alerts.map((alert) => <Alert {...alert} />)}
</>
);
};
我正在尝试这样测试它:
test('An alert is rendered on a newalert event', () => {
render(<Alerts />);
fireEvent(
document,
createEvent('newalert', document,
{
details: {
body: 'Hello World!',
type: 'info',
timeout: 1000,
}
})
);
expect(screen.getByText('Hello world'));
});
它正在按预期触发自定义事件,但是 none 的属性(详细信息、正文、类型或超时)正在传递给事件。我错过了什么?
你需要将事件构造函数的名称作为第四个参数传递,并且有效!
createEvent(
'newalert',
document,
{
detail: {
body: 'Hello World!',
type: 'info',
timeout: 1000,
}
},
{ EventType: 'CustomEvent' }
)
);
我正在尝试使用 RTL 测试组件,该组件使用 customEvent 来触发显示。给定这样的组件:
const Alerts = () => {
const [alerts, setAlerts] = useState([]);
const addAlert = (body, type = 'info', timeout = 7500) => {
const key = nextIndex++;
setAlerts([
...alerts,
{ key, body, type },
]);
// Set a timer to remove the alert.
setTimeout(() => {
setAlerts(alerts.filter((alert) => alert.key !== key));
}, timeout);
};
document.addEventListener(
'newalert',
({ details:
{
body = '',
type = '',
timeout = 1000
} = {}
}) => {
addAlert(body, type, timeout);
});
return (
<>
{alerts.map((alert) => <Alert {...alert} />)}
</>
);
};
我正在尝试这样测试它:
test('An alert is rendered on a newalert event', () => {
render(<Alerts />);
fireEvent(
document,
createEvent('newalert', document,
{
details: {
body: 'Hello World!',
type: 'info',
timeout: 1000,
}
})
);
expect(screen.getByText('Hello world'));
});
它正在按预期触发自定义事件,但是 none 的属性(详细信息、正文、类型或超时)正在传递给事件。我错过了什么?
你需要将事件构造函数的名称作为第四个参数传递,并且有效!
createEvent(
'newalert',
document,
{
detail: {
body: 'Hello World!',
type: 'info',
timeout: 1000,
}
},
{ EventType: 'CustomEvent' }
)
);