Unit testing your React application with Jest and Enzyme

import React from 'react';
import { string } from 'prop-types';const Link = ({ title, url }) => <a href={url}>{title}</a>;Link.propTypes = {
  title: string.isRequired,
  url: string.isRequired
};export default Link;
import React from 'react';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';import Link from './Link';describe('Link', () => {
  it('should render correctly', () => {
    const output = shallow(
      <Link title="mockTitle" url="mockUrl" />
    );
    expect(shallowToJson(output)).toMatchSnapshot();
  });
});
// Jest Snapshot v1, https://goo.gl/fbAQLPexports[`Link should render correctly 1`] = `
<a
  href="mockUrl"
>
  mockTitle
</a>
`;
import React, { Component } from 'react';
import { string } from 'prop-types';class Link extends Component {
  handleClick() => {
    alert('clicked!');
  };  render() {
    const { title, url } = this.props;
    return <a href={url} onClick={this.handleClick}>{title}</a>;
  }
}
exports[`Link should render correctly 1`] = `
<a
  href="mockUrl"
  onClick={[Function]}
  target=""
>
  mockTitle
</a>
`;
it('should handle the click event', () => {
  window.alert = jest.fn();
  const output = shallow(
    <Link title="mockTitle" url="mockUrl" />
  );
  output.simulate('click');
  expect(window.alert).toHaveBeenCalledWith('clicked');
});
class Link extends Component {
  constructor(props) {
    super(props);
    this.state = { clicked: false };
  }  handleClick = () => {
    alert('clicked');
    this.setState({ clicked: true });
  }
  ...
}
it('should handle state changes', () => {
  const output = shallow(
    <Link title="mockTitle" url="mockUrl" />
  );
  
  expect(output.state().clicked).toEqual(false);
  output.simulate('click');
  expect(output.state().clicked).toEqual(true);
});
import React from 'react';
import { render } from 'react-dom';
import Link from './Link';jest.mock('react-dom');describe('Link', () => {
  it('should render correctly', () => {
    expect(render).toHaveBeenCalledWith(
      <Link title="mockTitle" url="mockUrl" />, 'element-node'
    );
    expect(render).toHaveBeenCalledTimes(1);
  });
});
export default {
  render: jest.fn(),
};
render: jest.fn().mockReturnValue('component is rendered'),render: jest.fn().mockImplementation(() => 'mock implementation'),

wehkamp-techblog

We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out https://werkenbij.wehkamp.nl/

Berry de Witte

Written by

Senior Front-end developer @ Wehkamp.nl

wehkamp-techblog

We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out https://werkenbij.wehkamp.nl/