简体   繁体   中英

Mocha, Enzyme: Unit testing custom functions in react component using enzyme

I am working on creating unit tests of react components using mocha, enzyme. Below is a sample component.

Foo.js

class Foo extends React.Component {
    customFunction=() => {
    }

    render() {
        return (<div className={this.props.name}/>);
   }
}

And here is the testing file.

Foo-Test.js

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Foo from '../src/Foo';

describe("A suite", function() {
    it("contains spec with an expectation", function() {
        expect(shallow(<Foo />).contains(<div className="foo" />)).to.equal(true);
    });

    it("contains spec with an expectation", function() {
        expect(shallow(<Foo />).is('.foo')).to.equal(true);
    });
});

Everything is good. but I didn't understand how to unit test customFunction in Foo.js when we are using enzyme

The best answer to this question really depends on what it is that customFunction is actually doing...

You can call the function like this:

wrapper.instance().customFunction('foo', 'bar');

If it's a function that sets state on the instance itself, and thus affects what the rendered output looks like, you may want to call .update() as well

wrapper.instance().customFunction('foo', 'bar'); // uses setState internally
wrapper.update(); // updates render tree
// do assertions on the rendered output

You can also use the chai plugin to spy on custom functions in you jsx file.

// to use this pluggin add this to the top of your testing file

const chai = require("chai"), spies = require("chai-spies");
chai.use(spies);
import Foo from "./<path to component>/Foo.jsx";

describe("Foo", () => {
  it("a call to customFunction will not error", () => {
    let spy = chai.spy(Foo.prototype, "customFunciton"); // spy
    const wrapper = mount(<Foo/>);
    wrapper.setProps({bar: "baz"}); // manipulate you component in some way
    expect(spy).to.have.been.called.once();
  });
});

@leland-richardson is right, it depends on what your test is doing. Understanding that will help you compose new ways to manipulate your component and thus make assertions.

Another example testing a function that updates your components state.

it("function will assert new state", () => {
  const wrapper = shallow(<Foo {...props}/>);
  wrapper.instance.customFunction(); // call custom function
  wrapper.update();
  expect(wrapper.state("bar")).to.equal("new-state");
});

Chai-spies also has a handful of chainable getters that make testing custom functions much easier. Please see the docs for a more in-depth explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM