Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Typescript React Component context with enzyme

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?

like image 916
besrabasant Avatar asked Sep 04 '26 07:09

besrabasant


1 Answers

The issue is resolved with help from the enzyme team.

Please refer to this Github Issue to know more about the solution.

like image 145
besrabasant Avatar answered Sep 07 '26 05:09

besrabasant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!