gpt4 book ai didi

javascript - Enzyme 在浅层渲染的 React 组件上为 prop 返回 null

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:29 24 4
gpt4 key购买 nike

问题

我刚刚开始进行 enzyme 和 react 测试。我正在尝试让 enzyme 与 karma 和 webpack 在一个简单的 react 组件上一起工作。我的问题是包装器上的 prop() 返回 null,我不确定为什么。

Greeter.js

import React from 'react';

/*
* A trivial component we added while trying to get the react testing working
* */

export default class Greeter extends React.Component {
constructor(props) {
super(props);
this.state = { name: props.initialName };

this.greeterText = this.greeterText.bind(this);
}

greeterText() {
return (<p>Hello, {this.state.name}!</p>);
}

render() {
return (<div className="greeter">
{this.greeterText()}
</div>);
}
}

Greeter.defaultProps = { initialName: "World" };

Greeter.propTypes = {
initialName: React.PropTypes.string
};

greeter.spec.js

import Greeter from '../../components/test/Greeter';
import React from 'react';
import { shallow } from 'enzyme';


describe("Simple testing with shallow rendering", () => {
beforeEach(function() {
let initialName = "joe";
this.wrapper = shallow(<Greeter initialName={initialName} />);
});

it("renders default Greeter", function() {
console.log(this.wrapper.find(".greeter").text());
console.log(this.wrapper.debug());
console.log(this.wrapper.state('name'));
expect(this.wrapper.state('name')).to.equal("joe");
expect(this.wrapper.prop('initialName')).to.equal("joe");
});
});

结果

Simple testing with shallow rendering × renders default Greeter Chrome 50.0.2661 (Windows 10 0.0.0) AssertionError: expected undefined to equal 'joe' at Assertion.assertEqual >>(F:/web/forms/node_modules/chai/chai.js:776:12) at Assertion.ctx.(anonymous function) [as equal] (F:web/forms/node_modules/chai/chai.js:4192:25) at Context. (F:web/forms/spec/components/greeter.spec.js:9:2932 <- webpack:///spec/components/greeter.spec.js:18:52)

堆栈

  • react 0.14.8
  • 业力
  • 网页包
  • enzyme 2.2.0

最佳答案

如果你想像这样测试传入的 Prop ,请像这样使用mount:

  it('allows us to set props', () => {
const wrapper = mount(<Foo bar="baz" />);
expect(wrapper.props().bar).to.equal("baz");
wrapper.setProps({ bar: "foo" });
expect(wrapper.props().bar).to.equal("foo");
});

关于javascript - Enzyme 在浅层渲染的 React 组件上为 prop 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37061887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com