Vasyl Gutnyk
Vasyl Gutnyk

Reputation: 5039

How do you test, mock context in React tests?

I have code like that:

render () {
  ...

  const {
    exampleMethod,
  } = this.props;

  const { getPath } = this.context;
  const exampletData = exampleMethod(getPath());

  ...
}

How can i mock, test context in this example? And how do you test context in general?

Upvotes: 1

Views: 3070

Answers (1)

WayneC
WayneC

Reputation: 5740

If you are using enzyme you can set the context when shallow rendering or full dom rendering by passing an option. (docs here):

eg:

import { shallow, mount } from 'enzyme';

// ......

const testContext = { getPath: () => 'foo' };
const shallowWrapper = shallow(<SomeComponent />, { context: testContext });

// or 

const fullWrapper = mount(<SomeComponent />, { context: testContext });

If you want to test the context on a node you can use the .context() method from enzyme

Upvotes: 6

Related Questions