chai-shallowly
一个用于 Enzyme 的 Chai 断言插件。该插件的目标是允许您在 Enzyme 中使用类似 Chai 的语法。
语法如下
let component = <Foo />;
expect(component).to.shallowly.haveClass("this-is-a-class");
如果您想浅渲染某些内容并使用此 API,您**必须**包含关键字 shallowly
。其余部分应该按预期工作。
注意:这不会改变 Chai 的上下文。 expect(component).to.shallowly.be.ok
将针对组件进行检查,而不是其浅层版本。这是一个有意设计的选择。
与 Karma 和 Webpack 集成
Enzyme 目前不希望捆绑在一个大型文件中。这会导致 Karma 和 Webpack 出现问题。您可能会看到数百条几乎毫无意义的错误消息,这些错误消息归结为以下几点
- Webpack 期望宣布一些全局变量。
- Webpack 需要**不**解析 sinon 而是直接导入它。
这是我们使用的配置(您可以在源代码中查看完整配置)
externals: {
jsdom: "window",
cheerio: "window",
"react/lib/ExecutionEnvironment": true,
"react/lib/ReactContext": true
},
resolve: {
alias: {
sinon: require.resolve("sinon/pkg/sinon")
}
},
module: {
noParse: [
/node_modules\/sinon\//
]
}
如果您想让 Enzyme(和 chai-enzyme)与 Karma 和 Webpack 一起使用,您需要将这些添加到您的测试专用配置中。
API
您可以查看测试以获取更明确的覆盖范围和用法。在这里,我将介绍我们迄今为止所做的事情。
// hasClass
expect(shallow(component).hasClass("class")).to.be.true;
expect(component).to.shallowly.haveClass("class");
// text
expect(shallow(component).text()).to.equal("text");
expect(component).to.shallowly.have.text().equal("text");
// is
expect(shallow(component).is("div")).to.be.true;
expect(component).to.shallowly.match("div");
// type
expect(shallow(component).type("div")).to.be.true;
expect(component).to.shallowly.have.type("div");
// find
expect(shallow(component).find(".foo")).to.have.length(2);
expect(component).to.shallowly.find(".foo").to.have.length(2);
// filter
expect(shallow(component).find(".foo").filter(".bar")).to.have.length(1);
expect(component).to.shallowly.find(".foo").filter(".bar").to.have.length(1);
// not
expect(shallow(component).find(".foo").not(".bar")).to.have.length(1);
expect(component).to.shallowly.find(".foo").without(".bar").to.have.length(1);
// contains
expect(shallow(component).contains("div")).to.be.true;
expect(component).to.shallowly.containJSX("div");
// state
expect(shallow(component).state(state)).to.eql({"foo": "bar"});
expect(component).to.shallowly.have.state(state).eql({"foo": "bar"});
// props
expect(shallow(component).instance().props(propKey)).to.eql(propValue);
expect(component).to.shallowly.have.props(propKey).eql(propValue);
// simulate
/* all of this */
var shallowComponent = shallow(component);
shallowComponent.simulate("click");
expect(shallowComponent.state()).to.eql({"state":"clicked"});
/* vs */
expect(component).to.shallowly.on("click").have.state().eql({"state":"clicked"});
// setState / setProps
var shallowComponent = shallow(component);
shallowComponent.setState(state);
expect(shallowComponent.state()).to.equal(state);
expect(component).to.shallowly.withState(state).to.have.state().equal(state);