我在 Typescript 中有一个 React Component ,就像这样
import * as React from 'react';
import * as PropTypes from 'prop-types';
export class MyComponent extends React.Component<{}, {}> {
context = {
callBack: Function
}
static contextTypes = {
callBack: React.PropTypes.Func
};
render() {
return (
<button onClick={this.callContextCallback}>Call Context</button>
);
}
callContextCallback = () => {
this.context.callBack();
}
}
我已经为Component
编写了测试import { mount, shallow } from 'enzyme'
import * as React from "react"
import { MyComponent } from "./MyComponent"
describe(`<MyComponent />`, () => {
let callBackMock = jest.fn()
beforeEach(() => {
wrapper = mount(
<MyComponent />, {
context: {
callBack: callBackMock
}
}
)
})
it(`should call context Callback on clicking button`, () => {
wrapper.find('button').simulate('click')
expect(callBackMock).toHaveBeenCalledTimes(1)
})
})
当我运行测试时,测试失败,函数未被调用。
我甚至试图在callContextCalback
功能
it(`should call context Callback on clicking button`, () => {
let instance = wrapper.instance()
const spy = jest.spyOn(instance, 'callContextCallback')
instance.forceUpdate();
wrapper.find('button').simulate('click')
expect(spy).toHaveBeenCalledTimes(1)
})
并且在运行测试时出现此错误
Error: Uncaught [TypeError: Cannot read property 'context' of undefined]
TypeError: Cannot read property 'context' of undefined
如何测试上下文callBack
功能?