2017-04-06 3 views
10

最近ReactコンポーネントのcomponentDidMountメソッドで条件付きで呼び出されるカスタムメソッドがいくつかあることをテストしたいと思っていました。Jestを使用してcomponentDidMountのメソッド呼び出しを偵察する

componentDidMount() { 
    if (this.props.initOpen) { 
    this.methodName(); 
    } 
} 

私はモック/スパイのためのjest.fn()が含まれて私のテストフレームワークとして冗談を使用しています。私は、これは、次のような何かを行うことによって、Sinonでテストすることはかなり些細なことだろうと読んだ:

sinon.spy(Component.prototype, "methodName"); 
const wrapper = mount(<Component {...props} />); 
expect(wrapper.instance().methodName).toHaveBeenCalled(); 

私はそうのような冗談でこれを再作成しようとしています:

Component.prototype.methodName = jest.fn(); 
const wrapper = mount(<Component {...props} />); 
expect(wrapper.instance().methodName).toHaveBeenCalled(); 

このコード次のエラーがスローされます。

jest.fn() value must be a mock function or spy. 
Received: 
    function: [Function bound mockConstructor] 

Jestでこの機能をテストすることはできますか?そしてもしそうなら、どうですか?

答えて

18

キーはjests spyOnメソッドを使用しています。ここに見られるような例えば

const spy = jest.spyOn(Component.prototype, 'methodName'); 
const wrapper = mount(<Component {...props} />); 
wrapper.instance().methodName(); 
expect(spy).toHaveBeenCalled(); 

:それはこのようにする必要がありTest if function is called react and enzyme

注意してください、また、各テスト実行

let spy 

afterEach(() => { 
    spy.mockClear() 
}) 

https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks

後にスパイ機能をオフにすることがベストプラクティスです
+0

ありがとうございました!それはちょうど数ヶ月前、19.0.0でちょうど出てきたようです。私はドキュメントでそれをスキップしたとは思わない。 – seansean11

+0

あなたは歓迎です – Jonathan

+0

コンポーネントの 'methodName()'関数を実際に呼び出すか、それともそれを偽っているのでしょうか? – prime

1

私は少し遅れていることを知っていますが、これを見つけたので、componentDidMountを呼び出してあなたはmethodNamecomponentDidMount経由で呼び出されたことを、あなたの主張、その後componentDidMountを呼び出すと良い

it('should call methodName during componentDidMount',() => { 
    const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName'); 
    const wrapper = mount(<MyComponent {...props} />); 
    expect(methodNameFake).toHaveBeenCalledTimes(1); 
}); 

-

モジュール

componentDidMount() { 
    if (this.props.initOpen) { 
    this.methodName(); 
    } 
} 

テスト:テストのようなものになりますあなたのネストされた方法より有効です。

テスト - バート

it('should call methodName during componentDidMount',() => { 
    const spy = jest.spyOn(Component.prototype, 'methodName'); 
    const wrapper = mount(<Component {...props} />); 
    wrapper.instance().methodName(); 
    expect(spy).toHaveBeenCalled(); 
} 

次のようにテストを書くことで - あなたがメソッドを呼び出し、それが呼ばれたと主張しています。もちろん、それはあなたにちょうどそれを呼んで与えているでしょう。

+0

これらのテストはどちらもうまくいっていませんが、一切合格できません – Byrd

+0

コンポーネントに必要なすべての小道具を渡していますか? – hloughrey

+0

最後に、それを使用してインスタンスを作成し、私のスパイにforceUpdateを作成する必要がありました。 – Byrd

関連する問題