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?
Aucun commentaire:
Enregistrer un commentaire