Alex Yong
Alex Yong

Reputation: 7645

Unit testing with enzyme got Cannot read property 'be' of undefined

My not working test

import React from 'react';
import {shallow, mount} from 'enzyme';
import TopNav from '../components/topNav';

it('Navbar should existed', () => {
    const nav = shallow(<TopNav />);
    expect(nav.find('#topNav').exists()).to.be(true);
});

My topNav Component.

import { Component } from 'react';

export default class topNav extends Component {
    render(){
        return(
            <div id="topNav"><strong className="testtest">Nav bar</strong></div>
        )
    }
}

I have no clue what is wrong here. I took the exact example from the API doc of enzyme. But when I do this, it worked

it('Navbar should existed', () => {
    expect(shallow(<TopNav />).is('#topNav')).toBe(true);
});

This is what the doc says http://airbnb.io/enzyme/docs/api/ShallowWrapper/exists.html

Upvotes: 0

Views: 484

Answers (1)

Yo Wakita
Yo Wakita

Reputation: 5450

Are you using Jasmine or Chai? You say that

it('Navbar should existed', () => {
    expect(shallow(<TopNav />).is('#topNav')).toBe(true);
});

works, and .toBe is a Jasmine expect assertion function. And the equivalent for Chai (which I think you're not using) is to.be. This is why to is undefined for you. Change your to.be to toBe, and it should work.

import React from 'react';
import {shallow, mount} from 'enzyme';
import TopNav from '../components/topNav';

it('Navbar should existed', () => {
    const nav = shallow(<TopNav />);
    expect(nav.find('#topNav').exists()).toBe(true);
});

Upvotes: 2

Related Questions