Wondering what’s next for npm?Check out our public roadmap! »

shallow-with-context

0.4.1 • Public • Published

shallow-with-context

Build Status Coverage Status NPM package version code style: prettier

The module is temporary workaround for passing context in shallow rendering mode. The new React Context API is not supported in shallow rendering mode yet.

It use under hood Legacy Context API and to-aop module.

Installation

npm i shallow-with-context --save-dev

Usage

Context is object

You don't have to use createContext method from shallow-with-context module for context as object.

import { shallow } from 'enzyme';
import { withContext } from 'shallow-with-context';
import React from 'react';
 
const MyContext = React.createContext({ text: 'default' });
class Component extends React.Component {
  static contextType = MyContext;
  render() {
    return <div>{this.context.text}</div>
  }
}
 
describe('your description', () => {
  it('your spec', () => {
    const context = { text: 'new value' };
    const ComponentWithContext = withContext(Component, context);
 
    const wrapper = shallow(<ComponentWithContext />, { context });
 
    expect(wrapper).toMatchInlineSnapshot('<div>new value</div>');
  });
});

Context is primitive value

You have to use createContext method from shallow-with-context module for context as primitive value because Legacy Context API don't support primitive value.

import { shallow } from 'enzyme';
import { withContext, createContext } from 'shallow-with-context';
import React from 'react';
 
const MyContext = React.createContext('default');
class Component extends React.Component {
  static contextType = MyContext;
  render() {
    return <div>{this.context}</div>
  }
}
 
describe('your description', () => {
  it('your spec', () => {
    const context = createContext('new value');
    const ComponentWithContext = withContext(Component, context);
 
    const wrapper = shallow(<ComponentWithContext />, { context });
 
    expect(wrapper).toMatchInlineSnapshot('<div>new value</div>');
  });
});

API

withContext

Parameters

  • Component (React.Component|React.PureComponent|function|ReactObject)
  • context Object<string, *>

createContext

Parameters

  • value (*)

Install

npm i shallow-with-context

DownloadsWeekly Downloads

2,250

Version

0.4.1

License

ISC

Unpacked Size

21 kB

Total Files

7

Last publish

Collaborators

  • avatar