Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shallow render returns empty object, wrapper.debug() shows fully rendered component

My apologies if this is a duplicate, but I have not found the answer yet. I am trying to test a functional component that renders react-bootstrap components. The smoke test works fine, but trying to test if it renders the correct children has been tricky. I have been following the docs for shallow rendering, but my wrapper returns: ShallowWrapper {} even though wrapper.debug() returns:

<div id="header">
  <Navbar color="faded" tag="nav" expand={false}>
    <NavbarBrand id="logo" href="/" tag="a">
      <img src="logo.png" id="logo-img"  alt="stool-logo" />
      Scores
    </NavbarBrand>
    <div id="header-flex-container">
      <Nav tag="ul" vertical={false} />
    </div>
  </Navbar>
</div>

This is my component (still a WIP, please ignore unused imports):

import React from "react";
import { Nav, Navbar, NavLink, NavItem, NavbarBrand } from "reactstrap";
import Logo from "../assets/logo.png";

import "../styles/Header.css";

export default function Header() {
  return (
    <div id="header">
      <Navbar color="faded">
        <NavbarBrand id="logo" href="/">
          <img src={Logo} id="logo-img" alt="stool-logo" />
          Scores
        </NavbarBrand>
        <div id="header-flex-container">
          <Nav></Nav>
        </div>
      </Navbar>
    </div>
  );
}

And this is my test:

import React from 'react';
import { shallow, mount } from 'enzyme';
import { Nav, Navbar, NavLink, NavItem, NavbarBrand } from "reactstrap";

import Header from '../Header';

describe('Header', () => {
  it('renders without crashing', () => {
    shallow(<Header/>)
  });

  it('renders the navbar', () => {
    const wrapper = shallow(<Header />);
    console.log(wrapper);
    console.log(wrapper.debug());
    expect(wrapper.find(Navbar)).to.have.lengthOf(1);
  })
});

I am not totally sure where I am going wrong, since the component is being rendered properly. I have also tried using mount, but get the same error each time: TypeError: Cannot read property 'have' of undefined.

I have also tried expect(wrapper.hasClass('navbar')).toEqual(true) but get an actual of false. I tried using .dive() on the wrapper but get: TypeError: ShallowWrapper::dive() can not be called on Host Components

Any help would be very appreciated.

like image 300
ossiggy Avatar asked Jun 22 '26 08:06

ossiggy


1 Answers

Looks like you are using expect from Jest with chai style.

You have 2 options, you can either add chai to your project and add this import to your tests:

import { expect } from 'chai';

Or, you can rewrite your test like this:

expect(wrapper.find(Navbar).length).toEqual(1);
like image 119
Hamza El Aoutar Avatar answered Jun 24 '26 06:06

Hamza El Aoutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!