我有一个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
})
});
我希望它不应该设置状态,因为name
是false
更新:
我从文档中错过的一件事是:
要呈现的根组件必须具有
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
})
});