2017-07-28 10 views
0

Jestで関数のモックを作成する方法について質問があります。私は自分のページ上にReactコンポーネント内の異なる機能を呼び出す2つの要素を持っています。これらの関数の両方が同じ関数を呼び出し、小道具から渡されます。onFieldChanged。私はこれら2つの要素の変化をシミュレートし、props.onFieldChangedが呼び出されることを確認したいと思います。Jestの2つの異なるテストブロックで同じ関数を擬似します。

私が最初のテスト(以下の最初のテスト)を書くと、それはフライングカラーで渡されます。 2回目のテストを書くと、2回目のテストは合格しますが、最初のテストは失敗します。基本的に、私は両方のテストを同時に通過することはできません。どうにか私は偽物をリセットする必要がありますか?誰もこれを行う方法を知っていますか?

何がありますか?

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

あなたはいつもlowerTimeLimitで呼ばれているこの二つのインスタンスのコンポーネントメソッドをスパイすることができます@MaxMillington :( –

+0

を動作しませんでしたaddOneToStudyDaysを呼び出し、これらのメソッドがonFieldChangedを呼び出すかどうかを確認してください:) – dfee

+0

私は今、 'const spy = jest.spyOn(wrapper.instance()、 'handleInputFieldChanged');'を実行してスパイがと呼ばれる。 'handleInputFieldChanged'は間違いなく呼び出されています(そこにいくつかのconsole.logを投げました)が、まだ'予想されたモック関数が呼び出されたと言っています。 ' –

関連する問題