react shows wrong length (testing)

Issue

This Content is from Stack Overflow. Question asked by walee

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().cameras.length);
i get:

enter image description here

in my component i can add new cam without any problem.

this part 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 ?

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().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().cameras.length;
 expect(cameras).toBeGreaterThan(initialLength);

    console.log(cameras);

  });
});



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?