简体   繁体   English

测试Typescript使用酶反应组件上下文

[英]Testing Typescript React Component context with enzyme

I have a React Component in Typescript something like this 我在Typescript中有一个像这样的React组件

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 我已经为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 我甚至尝试在callContextCalback 函数上进行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)
    })

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 ? 如何测试上下文callBack 函数

The issue is resolved with help from the enzyme team. 团队的帮助下解决了这个问题。

Please refer to this Github Issue to know more about the solution . 请参阅此Github问题以了解有关该解决方案的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM