this.context在jest / Enzyme中为null

时间:2019-10-08 05:47:27

标签: javascript reactjs jestjs enzyme

我有一个react类,没有要渲染的东西。它很少有在函数内部使用const name = { this.context }的函数。但是,name(在下面的示例中)始终未定义。我不确定自己在做什么错。

我尝试设置上下文wrap.setContenxt({name: true}),但是仍然在调用函数时将this.context显示为{}

person.js

export class Person extends Component {
  constructor(props) {
    super(props);
  }

  someMethod() {
    const { name } = this.context;
    const { record } = this.props;

    if (record && name) {
      this.setState({
        awesome: true
      });
    }
  }

  componentDidMount() {}

  render() {
    return null
  }
}

test.js

describe("this.context test", () => {

  const props = { record: true }
  const context = { name: false }

  it('should test someMethod()', () => {
    const wrap = shallow( <Person {...props} />, {context})
    const instance = wrap.instance()

    instance.someMethod();
    expect(instance.state.awesome).toBe(true) // pass

  })   
});

我希望它不应该设置状态,因为namefalse

更新
我从文档中错过的一件事是:

  

要呈现的根组件必须具有contextTypes静态属性。

基于此,如果我按照以下方式更新test.js,它将起作用:

describe("this.context test", () => {
   // ***this was missing***
   Person.contextTypes = {
      name: PropTypes.boolean
   };

  const props = { record: true }
  const context = { name: false }

  it('should test someMethod()', () => {
    const wrap = shallow( <Person {...props} />, {context})
    const instance = wrap.instance()

    instance.someMethod();
    expect(instance.state.awesome).toBe(true) // fail

  })   
});

0 个答案:

没有答案