反应:如何在类之外访问props对象?

时间:2019-02-14 20:49:56

标签: reactjs jestjs enzyme

我不确定如何在接收孩子的上下文之外访问props对象,有什么办法吗?这是我设置用来测试的最小测试文件(Jest和Enzyme)。我在尝试通过this.props.propNumber

传递"this is a reserved word"时遇到语法错误
const React = require("react");
const enzyme = require("enzyme");
const Adapter = require("enzyme-adapter-react-16");

enzyme.configure({ adapter : new Adapter() });

// simple component with an increment method
class Foo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      testIncrement : 1
    };
  }

  handleIncrement = (incrementSize) => {
    this.setState({
      testIncrement : this.state.testIncrement += incrementSize
    })
  };

  render() {
    return (
      <div>
        Test
      </div>
    );
  }
}


const wrapper = enzyme.shallow(
  <Foo
    propNumber={5}
  />
);


test('prop passage into shallow instance', () => {


wrapper.instance().handleIncrement(this.props.propNumber);

  expect(wrapper.state('testIncrement')).toEqual(6);
});

2 个答案:

答案 0 :(得分:2)

您知道道具是什么,因为您正在传递它,为什么需要从班级访问它呢?

const incrementSize = 1;
const propNumber = 5;

const wrapper = enzyme.shallow(
  <Foo
    propNumber={propNumber}
  />
);

test('prop passage into shallow instance', () => {
  wrapper.instance().handleIncrement(incrementSize);
  expect(wrapper.state('testIncrement')).toEqual(propNumber + incrementSize);
});

您的handleIncrement函数不使用数组,因此没有理由将其传递给它。

答案 1 :(得分:0)

在父组件文件中,导出值,然后在子组件文件中,导入值

相关问题