Skip to content

Testing with Jest and Enzyme

Thomas Harper edited this page May 27, 2020 · 1 revision

Testing with Jest and Enzyme

Running the tests

  • Run the following command:
npm test

Note you will need node installed first, if it is not run:

npm install

How we did the setup

  1. Installation

Enter the following commands in your terminal in the root directory of the project:

npm i --save-dev enzyme enzyme-adapter-react-16
npm install --save-dev jest-enzyme
  1. Create the setup file

Create the file ./src/setupTests.js and add the following code:

// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import "jest-enzyme";

configure({ adapter: new Adapter() });
  1. Creating a test file

You must start your tests with the following code:

// using enzyme
import React from 'react';
import { shallow } from "enzyme";

// using react-testing-library
import { render } from "@testing-library/react";

Example test

import React from 'react'
import Game from './game.js'
import { shallow } from 'enzyme'

it("renders without crashing", () => {
  shallow(<Game />);
});

describe('the game', () => {
  it('it asks for ctrl-c', () => {
    const wrapper = shallow(<Game />)
    const challenge = <p>Copy</p>
    expect(wrapper).toContainReact(challenge)
  })
})

Clone this wiki locally