1

In React 18 strict mode, Component first mounts, unmount and remount again. I want to add a test case in my React app to test this behaviour.

I am using karma, jasmine frameworks in my application. Currently didn't find how can we mount. So using ReactDOM.render()

    act(() => {
        ReactDOM.render(
            <Component />, container);
    });

    // Act
    act(() => {
        ReactDOM.unmountComponentAtNode(container);
    });

    act(() => {
        ReactDOM.render(
            <Component />, container);
    });

The problem is that, Although it is going inside the mounted hook, unmounted and also again mounted when remounting. But with render it is running again and say we have variable private a = ''; We are setting some Value in mounted and not cleaning in unmounted hook.

My expected output is when it remounts the variable shouldn't set to initial value as we are not cleaning it. But currently with render it's setting to null.

So is there anything I am missing to get my desired output

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Kotana Sai
  • 1,207
  • 3
  • 9
  • 20

1 Answers1

0

Didn't find anything useful, So changed my approach and one of the work around is to call the lifecycle hooks from the test file.

const component = new Component({ prop1: {' '}});
component.componentWillUnmount();
component.componentDidMount();

Although it doesn't look that good calling lifecycle hooks manually, this workaround get's my desired output.

If anyone know another approach, Please update the response.

Kotana Sai
  • 1,207
  • 3
  • 9
  • 20