[英]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.