2017-07-28 30 views
0

我有一个关于在Jest中创建函数模拟的问题。我的页面上有两个元素在我的React组件中调用不同的函数。这两个函数都调用了从道具onFieldChanged传入的相同函数。我想模拟这两个元素的变化,并确认props.onFieldChanged被调用。嘲笑Jest中两个不同测试块中的相同函数

当我编写第一个测试(下面的第一个测试)时,它通过了大量的颜色。当我编写第二个测试时,第二个测试通过但第一个测试失败。基本上,我不能同时通过两个测试。我需要重新设置模拟吗?有谁知道如何做到这一点?

什么给?

describe('user selects checkbox',() => { 
    props.onFieldChanged = jest.fn(); 
    const wrapper = shallow(<DateOptions {...props} />); 
    it('calls the onFieldChanged function',() => { 
     const element = wrapper.find('#addOneToStudyDays'); 
     element.simulate('change'); 
     expect(props.onFieldChanged).toHaveBeenCalled(); 
    }); 
    }); 

    describe('user types in input',() => { 
    props.onFieldChanged = jest.fn(); 
    const wrapper = shallow(<DateOptions {...props} />); 
    it('calls the onFieldChanged function',() => { 
     const element = wrapper.find('#lowerTimeLimit'); 
     element.simulate('change'); 
     expect(props.onFieldChanged).toHaveBeenCalled(); 
    }); 
    }); 

回答

0

试图通过jest.fn()为不同的变量:

describe('user selects checkbox',() => { 
    it('calls the onFieldChanged function',() => { 
     const onFieldChanged = jest.fn(); 
     const wrapper = shallow(<DateOptions {...props, onFieldChanged} />); 
     const element = wrapper.find('#addOneToStudyDays'); 
     element.simulate('change'); 
     expect(props.onFieldChanged).toHaveBeenCalled(); 
    }); 
    }); 

    describe('user types in input',() => { 
    it('calls the onFieldChanged function',() => { 
     const onFieldChanged = jest.fn(); 
     const wrapper = shallow(<DateOptions {...props, onFieldChanged} />); 
     const element = wrapper.find('#lowerTimeLimit'); 
     element.simulate('change'); 
     expect(props.onFieldChanged).toHaveBeenCalled(); 
    }); 
    }); 
+0

没有工作:( –

+0

@MaxMillington你总是可以在其上由lowerTimeLimit叫这两个实例组件的方法窥探和addOneToStudyDays,然后检查是否这些方法调用onFieldChanged :) – dfee

+0

我试着通过做'const spy = jest.spyOn(wrapper.instance(),'handleInputFieldChanged');'然后期待间谍已经调用。 'handleInputFieldChanged'肯定被调用(扔了一些console.logs在那里),但它仍然说'预期的模拟函数被调用。' –