I have a React Component in _Typescript_ something like this
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();
}
}
And I have written my tests for the 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)
})
})
when I run my tests, The test fails with function not being called.
I even tried mocking spying on the _callContextCalback_ function
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)
})
and on running the test I get this error
Error: Uncaught [TypeError: Cannot read property 'context' of undefined]
TypeError: Cannot read property 'context' of undefined
How do I test the context _callBack_ function?
| library | version|
| ---------------- | -------|
| Enzyme | 3.3.0 |
| React | 16.2.0 |
Try setting your context type to PropTypes.func (not Func)
But how do I spy on the context function?
And even after the changes, you suggested I still get the same errors
With the first test? The second one won鈥檛 work, because spies have to be created before creating the wrapper (and arrow functions in class properties should never be used, for multiple reasons including that they can鈥檛 be spied upon reliably)
After binding the function in constructor, the second on works. But I am still not able to run successful assertions against the context callback function
Can you share the updated component and test code?
My bad, It was some syntax error in my code. All the tests are now running fine. But had to remove _arrow functions_ and bind the _functions_ in the Component _constructor_ Thanks. :blush:
Most helpful comment
My bad, It was some syntax error in my code. All the tests are now running fine. But had to remove _arrow functions_ and bind the _functions_ in the Component _constructor_ Thanks. :blush: