2017-02-24 11 views
5

私はモカから冗談にスワッピングしていて、反応方法を偵察する方法があるのだろうかと思っています。例えば、私は私のコンポーネントで次のメソッドを持っていると言う(SDKライブラリを無視し、それだけでjqueryのAJAX呼び出しを構築する)ことができます:Jest spy on functionality

getData() { 
    sdk.getJSON('/someURL').done(data => { 
     this.setState({data}); 
    }); 
} 

sinonを使用して、私はそうのようなプロトタイプをスパイすることでこれをテストします:

it('should call getData',() => { 
     sinon.spy(Component.prototype, 'getData'); 
     mount(<Component />); 
     expect(Component.prototype.getData.calledOnce).to.be.true; 
    }); 

これは、メソッドを嘲笑せずにコードカバレッジを保証します。 jestにも同様の機能がありますか?

編集:また、この機能が存在しない場合、API呼び出しをテストするための次善策は何ですか?

答えて

6

あなたはあなたが新しいspyOn方法のために行くことができ

3

を探しているか、次の必要がありますも正常に動作している正確に何をしている、それが何日か前にV19で導入された、spyOn方法があります。メソッドが呼び出された場合

it('should call getData',() => { 
    Component.prototype.getData = jest.fn(Component.prototype.getData); 
    expect(Component.prototype.getData).toBeCalled(); 
}); 
+0

これは同じ動作ではありません'sinon.spy'のように' getData'を上書きし、 'sinon.spy'と' jest.spyOn'も元のメソッドを呼び出します。 –

+0

正解!答えを修正しました –

1

実はあなたはjest.spyOn jest.spyOn

を使用することができたときにコンポーネント作成に使用:

import { mount } from 'enzyme'; 

describe('My component',() => { 
    it('should call getData',() => { 
    const spy = jest.spyOn(Component.prototype, 'getData'); 
    mount(<Component />); 
    expect(Component.prototype.getData).toHaveBeenCalledTimes(1) 
    }); 
}) 

か、あなたのDOMおよび方法の使用にバインドそれを持っている場合使用できる:

import { shallow } from 'enzyme'; 

describe('My component',() => { 
    it('should call getData',() => { 
    const wrapper = shallow(<Component />); 
    const instance = wrapper.instance() 
    const spy = jest.spyOn(instance, 'getData'); 
    wrapper.find('button').simulate('click') 
    expect(spy).toHaveBeenCalledTimes(1) 
    }); 
})