samedi 24 août 2019

How do I test the method shouldComponentUpdate?

I would like to test out the method, shouldComponentUpdate but the test I wrote doesn't catch the side effects. How do I test this?

I have tried the solution proposed here but there are issues with it which I will show in the code: How to unit test React Component shouldComponentUpdate method

I have tried using shallow rather than mount but when I did that, my test fails at this point:

    expect(shouldComponentUpdate).to.have.property("callCount", 1);
    // AssertionError: expected [Function: proxy] to have a property 'callCount' of 1, but got 0

Here's my component's shouldComponentUpdate function:

    shouldComponentUpdate(nextProps, nextState) {
        if (this.props.storageValue !== nextProps.storageValue) {
            localStorage.setItem(constantFile.storageKey, nextProps.storageValue);
            localStorage.setItem(constantFile.timestampKey, now());
            this.setState({
                newStorage: nextProps.storageValue
            });
            return true;
        }

        ...

        return false;
    }

Here's my test:

    it("Test shouldComponentUpdate", () => {
        /* eslint-disable one-var */
        const wrapper = mount(
            <Provider store={store}>
                <MyComponent />
            </Provider>),
            shouldComponentUpdate = sinon.spy(CapitalHomeAccessPointContainer.prototype, "shouldComponentUpdate");
        wrapper.setProps({
            storageValue: true
        });
        expect(shouldComponentUpdate).to.have.property("callCount", 1);   
        expect(shouldComponentUpdate.returned(true)).to.be.equal(true);
  expect(localStorage.getItem(constantFile.timestampKey)).to.equal(someExpectedTimestamp);
    });

expect(shouldComponentUpdate).to.have.property("callCount", 1);

fails with

AssertionError: expected false to equal true

Why does this happen? I thought shouldComponentUpdate should have returned true? Later, I'm hoping to test the state and local storage side effects but I do not understand this error.

Aucun commentaire:

Enregistrer un commentaire