Alister
Alister

Reputation: 463

React Enzyme Props Not Set on Mount

I am writing unit tests for a HOC that renders a chart and performs some operations on it. The chart is generated using data acquired from the database and stored in the redux-store. For the purposes of testing I have created a fake data store, however loading data for the chart occurs at componentDidMount and is performed by checking the value of a prop. So my code is as follows:

...
ComponentDidMount()
{
    console.log(this.props.getData);

    if (this.props.getData === "YES")
        this.props.loadData();
}
...

And the code in my unit test is as follows:

...
const mockStore = configureStore([thunk]);
let fakeStore = mockStore({...});

it("loads data"), function() {
    let store = fakeStore;
    const options = {
        context: {store},
        childContextTypes: {store: PropTypes.object.isRequired},
    };
    const mounted = mount(<Component getData="YES"/>, options);
    console.log(mounted.props());
    mounted.instance().componentDidMount();
}
...

The problem is using console.log I can see the props are not set when the component is first mounted and componentDidMount runs automatically, despite me specifying some values, but the props are immediately after, and when I attempt to call the function, it does not run, yet no messages are displayed explaining why exactly it didn't.

Could someone please advise?

Upvotes: 1

Views: 704

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may mock the external interaction using the Sinon library. Then check whether mock interaction is invoked when the component is rendered. What you are writing is a unit test not an end to end test. So it should be like this:

import React from 'react'
import YourComponent from 'components/YourComponent'
import { shallow } from 'enzyme'
describe('(Component) YourComponent', () => {
  let _props, _spies, _wrapper

  beforeEach(() => {
    _spies = {}
    _props = {
      prop1: 'value1',
      prop2: 'value2',
      ...
      getData : (_spies.getData = sinon.spy()),
    }
    _wrapper = shallow(<YourComponent {..._props} />)
  })


  it('Should trigger the `getData` callback when mounted', () => {
    _spies.getData.should.have.been.called
  })

})

Upvotes: 1

Related Questions