简体   繁体   English

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

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

I have a following class component: 我有以下课程内容:

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

Where essentially I call methodA to call methodB with certain parameters I have to pass it. 基本上在哪里我叫methodA调用methodB某些参数我要传递给它。

In Jest, I am having hard time writing test coverage where methodB has been called in methodB 在Jest中,我很难编写测试覆盖率,其中methodB已在methodBmethodB

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

What am I doing wrong? 我究竟做错了什么?

You are trying to hang spy on objest spyFn, that is completely unrelated to <HellowWorld/> . 您正在尝试将间谍挂在objest spyFn上,这与<HellowWorld/>完全无关。 Are you just want to spy on methodB in <HellowWorld/> ? 你只是想窥探methodB<HellowWorld/> If so, here are your test 如果是这样,这是您的测试

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

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

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