I am learning how to test components.
This is the component I'm trying to add tests to: https://github.com/sickdyd/react-dynamic-badge/tree/testing
This is the main file for the tests: https://github.com/sickdyd/react-dynamic-badge/blob/testing/src/test/test/DynamicBadge.test.js
My component functionality depends on its parent element width. In particular it uses this function:
function getElementContentWidth(element) {
let styles = window.getComputedStyle(element);
let padding = parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);
return element.clientWidth - padding;
}
Which is called as follows in React.useLayoutEffect():
const containerW = getElementContentWidth( refContainer.current.parentNode );
Where refContainer is a div that wraps my component in the component render:
return <div data-testid="badge" ref={refContainer}>{ output }</div>
This is my test():
test("matches snapshot", ()=> {
// I found this here: https://reactjs.org/docs/test-renderer.html#ideas
// but I'm not really sure what this is doing...
function createNodeMock(element) {
if (element.type === 'div') {
return {
focus() {},
};
}
return <div></div>;
}
const options = { createNodeMock };
Object.defineProperty(window, 'getComputedStyle', {
value: () => ({
getPropertyValue: (prop) => {
return '';
}
})
});
const tree = renderer.create(
<div style=>
<DynamicBadge
items={[
"Item 1",
"Item 2",
"Item 3",
]}
/>
</div>
, options
).toJSON();
expect(tree).toMatchSnapshot();
});
The test fails at: return element.clientWidth - padding;
saying TypeError: Cannot read property 'clientWidth' of undefined
.
How can I make it work?
Aucun commentaire:
Enregistrer un commentaire