0
votes

I want to do some basic unit test to my app which I created with "create-react-app" package. I believe it already has Jest installed.

I have some basic redux code in my app.

I want to test:

  1. It renders the main component(App.js) without crashing

  2. Clicking to show next item funcion

I have installed Enzyme using "npm install --save-dev enzyme" and "enzyme-adapter-react-15".

Here is my code:

import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import { shallow, mount, render, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';

configure({ adapter: new Adapter() });

describe('A test for App component', () => {
 let wrapper

 beforeEach(()=>{
   wrapper = shallow(<App />);
 })

 it('should render App Component', () => {
   expect(wrapper).to.have.length(1)
 })
})

I can't get the test to start to work. The error message:

TypeError: Cannot read property 'length' of undefined

and

TypeError: Cannot read property 'have' of undefined

I think there is some basic things I am doing wrong.

Any help is appreciated!!!

2
I think that only doing a shallow(<App />) will test that the App component renders without crashing. If you need to check if a button is there, you can use find with a query selector and check its length. To simulate click it would look something like wrapper.find(Button).at(0).simulate('click') - erich
Hi Erich, I can't get the test that I am having to work. - Olivia

2 Answers

1
votes

You are using Jest's expect function. You need to explicitly declare the import from chai.

it will look something like:

import { expect } from 'chai'
it('should render App Component', () => {
    expect(wrapper).to.have.length(1)
})

Also, instead of adding the adapter configuration for each test, you could add a file setupTests.js to /src and it will work for all tests :-)

1
votes

You probably copied it from the examples on enzyme's website, which uses chai. The jest equivalent for what you're trying to test is:

it('should render App Component', () => {
   expect(wrapper).toHaveLength(1)
})