簡體   English   中英

Mocha,Enzyme:使用酶對反應組分中的定制功能進行單元測試

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

我正在使用mocha,酶來創建反應組分的單元測試。 下面是一個示例組件。

Foo.js

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

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

這是測試文件。

富-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);
    });
});

一切都是好的。 但是當我們使用酶時,我不明白如何在Foo.js中對customFunction進行單元測試

這個問題的最佳答案實際上取決於customFunction實際上在做什么......

您可以像這樣調用函數:

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

如果它是一個在實例本身上設置狀態的函數,從而影響渲染輸出的樣子,你可能也想調用.update()

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

您還可以使用chai插件監視jsx文件中的自定義函數。

// 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是對的,這取決於你的測試是做什么的。 理解這將有助於您構建操作組件的新方法,從而進行斷言。

測試更新組件狀態的函數的另一個示例。

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還有一些可連接的吸氣劑,可以更輕松地測試自定義功能。 請參閱文檔以獲得更深入的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM