It's my first time to write tests. I'm writing tests for a ReactJS app wrote with hooks, and testing using Jest and react-testing-library.
Here's my functional component:
const ItemDetails = ({ item }) => {
const { code } = item;
const { getBarcode } = useStationContext();
return (
<>
<Button
type="primary"
onClick={() => {
getBarcode(code);
}}
style={{ float: 'right' }}
>
Print Barcode
</Button>
<List
bordered
dataSource={formatData(item)}
renderItem={({ title, value }) => (
<List.Item>
<List.Item.Meta
description={
<Wrapper>
<p>{upperCase(title)}</p>
<div>{value}</div>
</Wrapper>
}
/>
</List.Item>
)}
/>
</>
);
};
export default ItemDetails;
and the test file:
import React from 'react';
import { render, cleanup } from 'react-testing-library';
import ItemDetails from '../containers/Items/ItemPage/ItemDetails';
afterEach(cleanup);
describe('formatData()', () => {
it('Return Details about item', async () => {
const { getByText, getByTestId, container, asFragment } = render(
<ItemDetails
item={{
id: '296-c-4f-89-18',
barcode: 'E-6',
}}
/>,
);
global.console = {
log: jest.fn(getByText, getByTestId, container, asFragment),
};
expect(global.console.log).toHaveBeenCalledWith('test');
});
});
When I run the test I got this error:
TypeError: Cannot read property 'getBarcode' of null
I don't know how can I fix this?
The expectations are wrong because console.log isn't called anywhere. Mocking console object like global.console = ... is a bad practice because it persists between tests and can break things that depend on it, including test runner itself.
There's inconsistency with item code key, it was provided as barcode.
Context value is expected to be undefined, unless default value was provided. It should be provided in test.
It likely should be:
const getBarcodeMock = jest.fn();
const { getByText, getByTestId, container, asFragment } = render(
<StationContext.Provider value={{ getBarcode: getBarcodeMock }}>
<ItemDetails
item={{
id: '296-c-4f-89-18',
code: 'E-6',
}}
/>
</StationContext.Provider>
);
// ...simulate button click...
expect(getBarcodeMock).toBeCalledWith('E-6');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With