Jest.js - 测试是否已调用组件方法(React.js)

Ale*_*dro 2 javascript tdd jasmine reactjs jestjs

我有一个以下类组件:

export class HelloWorld extends Component {
    constructor(props) {
        super(props)
        this.methodA = this.methodA.bind(this)
        this.methodB = this.methodB.bind(this)
    }

    methodA(props) {
        if (props.someValue === true) {
            ......
            methodB(props.someValue, true)
        } else {
            ......
            methodB(props.someValue, false)
        }
    }
    ...
    ...
}
Run Code Online (Sandbox Code Playgroud)

本质上,我调用methodA某些methodB参数时必须传递它。

在开玩笑中,我很难在methodB被调用的地方编写测试覆盖范围methodB

describe('componentA', () => {
    it('should call componentB', () => {
        const wrapper = enzyme.shallow(<HellowWorld {...(Object.assign(baseProps, { smsStatus: 'VALID' }))} />)

        const spyFn = {
            methodB: () => jest.fn()
        }
        const spyPreventDefault = jest.spyOn(spyFn, 'methodB')
        wrapper.instance().methodA(baseProps)
        expect(spyPreventDefault).toHaveBeenCalled()
    })
})
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

And*_*nko 5

您正在尝试将间谍挂在 objest spyFn 上,这与<HellowWorld/>. 你只是想监视methodB<HellowWorld/>?如果是这样,这是您的测试

describe('componentA', () => {
  it('should call componentB', () => {
    const wrapper = enzyme.shallow(<HellowWorld {...(Object.assign(baseProps, { smsStatus: 'VALID' }))} />)

    const spyPreventDefault = jest.spyOn(wrapper.instance(), 'methodB');
    wrapper.instance().forceUpdate();
    wrapper.instance().methodA(baseProps)
    expect(spyPreventDefault).toHaveBeenCalled()
  })
})
Run Code Online (Sandbox Code Playgroud)