Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React Native how can I test my components with Shallow Rendering?

Tags:

For React, I use Shallow Rendering techniques for unit testing my React components. Can I do something similar in React Native?

I've followed the instructions to set up Jest, but can't find any documentation on testing my components. I would like to do full TDD with React Native in the same way I do with React.

like image 681
ooolala Avatar asked Sep 27 '15 03:09

ooolala


People also ask

Does React testing library shallow render?

React Testing library Enzyme's shallow renderer doesn't render sub-components, so React Testing Library's render method is more similar to Enzyme's mount method. In React Testing Library, you don't need to assign the render result to a variable (i.e. wrapper ).

What does testing with shallow rendering mean?

Shallow rendering lets you render a component “one level deep” and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

Which of the following testing utility does the shallow rendering a useful constraint to test component as a unit?

Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components. As of Enzyme v3, the shallow API does call React lifecycle methods such as componentDidMount and componentDidUpdate .


Video Answer


2 Answers

I think enzyme is what you're looking for.

It provides you a shallow function which allows you to make a shallow comparison (as you want).

Enzyme can be used along with all of the popular test runners (like Mocha, Jest, Karma etc). Full list can be found on the library's github page.

Example:

import {shallow} from 'enzyme';

describe('<MyComponent />', () => {
  it('should render three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.length(3);
  });
});

For the further reading you can take a look on enzyme's Shallow Rendering API or docs in general.

like image 154
Alexey Kureev Avatar answered Sep 19 '22 15:09

Alexey Kureev


You can do this without using enzyme, just use Shallow Renderer from react-test-renderer.

import ShallowRenderer from 'react-test-renderer/shallow';

it('renders', () => {
  const renderer = new ShallowRenderer();
  const wrapper = renderer.render(<MyComponent />);

  expect(wrapper).toMatchSnapshot();
});
like image 32
Black Avatar answered Sep 18 '22 15:09

Black