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

时间:2018-03-01 15:37:51

标签: reactjs typescript testing enzyme

我在 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 功能

1 个答案:

答案 0 :(得分:1)

团队的帮助下解决了这个问题。

请参阅此Github Issue以了解有关解决方案的更多信息。