2017-07-28 31 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在那裏),但它仍然說'預期的模擬函數被調用。' –