【问题标题】:Jest.js - Testing if component method has been called (React.js)Jest.js - 测试组件方法是否被调用 (React.js)
【发布时间】:2018-04-04 03:34:53
【问题描述】:

我有以下类组件:

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

我做错了什么?

【问题讨论】:

    标签: javascript reactjs jasmine tdd jestjs


    【解决方案1】:

    您正试图在 objest spyFn 上挂起间谍,这与 &lt;HellowWorld/&gt; 完全无关。 你只是想在&lt;HellowWorld/&gt; 中监视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()
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      相关资源
      最近更新 更多