Learning react testing by coding (react testing library and jest), here i'm testing adding new camera, initial length before adding should be 3, but here console.log("initialLength", initialLength); it gives me 0, thats why also in testing it gives " Expected: > 0 Received: 0". My question is why it shows initialLength to be 0 ? if i check console in my component
console.log("storedd:", store.getState().site.cameras.length); i get:
in my component i can add new cam without any problem.
this part (also clicking submit button) works :
expect(name).toBeInTheDocument(); fireEvent.change(name, { target: { value: "Cam 2" } }); expect(name).toHaveValue("Cam 2");
so why initialLength which is 3, it shows to be 0 and how to fix it to take 3 and not 0 ? and also after clicking submit/Accept button it still shows length to be 0.
English is not my mother language so could be mistakes, any advice is appreciated.
describe("Testing Cam", () => {
const rendercam = (): RenderResult =>
render(
<Provider store={store}>
<CameraForm
/>
</Provider>
);
test("Testing renderCams", () => {
rendercam();
const initialLength = store.getState().site.cameras.length;
console.log("initialLength", initialLength);
const name = screen.getByTestId(/^Name/i);
expect(name).toBeInTheDocument();
fireEvent.change(name, { target: { value: "Cam 2" } });
expect(name).toHaveValue("Cam 2");
let submitButton = screen.getByTestId("submit");
fireEvent.click(
submitButton,
new MouseEvent("click", {
bubbles: true,
cancelable: true,
})
);
let cameras = store.getState().site.cameras.length;
expect(cameras).toBeGreaterThan(initialLength);
console.log(cameras);
});
});
CameraForm:
export function CameraForm(props) {
console.log("initialLength", store.getState().site.cameras.length);
const handleSubmit = (event) => {
event.preventDefault();
const { name } = state;
refreshCameraList();
dispatch<any>(
addCamera(site.identifier, {
name,
site_id: site.identifier,
client_config: clientConfig,
})
);
externalOnSubmit();
};
const Add = () => {
const { name, } = state;
return (
<React.Fragment>
<Box >
<form
onSubmit={handleSubmit} >
<div >
<Box >
<Button
onClick={nulll}
aria-label="close-settings-popup">
<Close />
</Button>
</Box>
</div>
<div >
<FormGroup>
<Box>
<FormControl>
<TextField
inputProps={{
"data-testid": "Name",
}}
type="text"
id="name"
value={name}
onChange={handleChange}
label={<Trans i18nKey="formData.name">Name</Trans>}
></TextField>
</FormControl>
</Box>
</FormGroup>
</div>
{!state.readOnly ? (
<div>
<Button
// style={{ flex: "1" }}
onClick={nulll}
variant="outlined">
Cancel
</Button>
<Button
data-testid="submit"
type="submit"
disabled={
!site ||
Object.values(state.error).some((v) => {
return v === true;
})
}
startIcon={<Done />}
>
Accept
</Button>
</div>
) : (
""
)}
</form>{" "}
</Box>
</React.Fragment>
);
};
const option = props.mode;
return (
<div data-testid="header">
{option === ADD ? Add() : <></>}
{option === UPDATE ? Update() : <></>}
</div>
);
}
