首页 > 解决方案 > ShallowWrapper is empty when running test

问题描述

I'm new to testing so I'm trying to add Enzyme to one of my projects. My problem is that when using find(), the ShallowWrapper is empty. Also I'm using Material UI, so I don't know if this is part of the problem.

The component I'm testing

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";

const styles = theme => ({
  root: {
    flexGrow: 1
  },
  background: {
    backgroundColor: "#2E2E38"
  },
  title: {
    color: "#FFE600",
    flexGrow: 1
  }
});

const NavBar = ({ classes }) => {
  return (
    <div className={classes.root} data-test="nav-bar">
      <AppBar className={classes.background}>
        <Toolbar>
          <Typography variant="h5" className={classes.title}>
            App
          </Typography>
        </Toolbar>
      </AppBar>
    </div>
  );
};

export default withStyles(styles)(NavBar);

The test

import React from "react";
import { shallow } from "enzyme";
import NavBar from "./NavBar";

describe("NavBar component", () => {

  it("Should render without errors.", () => {
    let component = shallow(<NavBar />);
    let navbar = component.find("data-test", "nav-bar");
    console.log("Log is", component);
    expect(navbar).toBe(1);
  });
});

标签: reactjsunit-testingmaterial-uienzyme

解决方案


Try changing your selector in find(selector) to the following to target the element with data-test="nav-bar". You may need to use dive() to be able to access the inner components of the style component:

import React from "react";
import { shallow } from "enzyme";
import NavBar from "./NavBar";

describe("NavBar component", () => {

  it("Should render without errors.", () => {
    const component = shallow(<NavBar />);
    // Use dive() to access inner components
    const navbar = component.dive().find('[data-test="nav-bar"]');
    // Test that we found a single element by targeting length property
    expect(navbar.length).toBe(1);
  });
});

You can also use an object syntax if you prefer:

const navbar = component.find({'data-test': 'nav-bar'});

Alternatively to using dive(), you could instead mount() the component instead of shallow(), but it depends on your use case:

import React from "react";
import { mount } from "enzyme";
import NavBar from "./NavBar";

describe("NavBar component", () => {

  it("Should render without errors.", () => {
    const component = mount(<NavBar />);
    // Use dive() to access inner components
    const navbar = component.find('[data-test="nav-bar"]');
    // Test that we found a single element by targeting length property
    expect(navbar.length).toBe(1);
  });
});

Hopefully that helps!


推荐阅读