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

Jest.js - Testing if component method has been called (React.js)

我有以下 class 组件:

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)
        }
    }
    ...
    ...
}

基本上我调用 methodA 来调用 methodB 时必须传递某些参数。

在 Jest 中,我很难编写 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()
    })
})

我做错了什么?

您正试图在 objest spyFn 上挂起间谍,这与 <HellowWorld/> 完全无关。 你只是想监视 <HellowWorld/> 中的 methodB 吗? 如果是这样,这是你的测试

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()
  })
})