web-dev-qa-db-ja.com

機能に関するジェストスパイ

私はモカからjestに交換していますが、反応メソッドをスパイする方法があるかどうか疑問に思っています。たとえば、コンポーネントに次のメソッドがあるとしましょう(sdkライブラリを無視し、jquery ajax呼び出しを作成するだけです):

    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呼び出しをテストするための次善の戦略は何ですか?

29
Jake

spyOn メソッドがあります。これは数日前にv19で導入されたもので、探しているものを正確に実行します。

17

実際には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およびメソッドで使用している場合bindを使用できます:

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)
  });
})
25
Denis Rybalka

新しいspyOnメソッドを使用することもできますが、次の方法でも問題なく動作するはずです。

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

React 16.8でJestを使用しています-これはうまくいきました:

  it("lifecycle method should have been called", () => {
    jest.spyOn(RedirectingOverlay.prototype, 'componentWillUnmount');
    jest.spyOn(RedirectingOverlay.prototype, 'componentDidMount');
    const wrapper = mount(<RedirectingOverlay message="Hi There!"/>);
    expect(RedirectingOverlay.prototype.componentDidMount).toHaveBeenCalledTimes(1)
    wrapper.unmount()
    expect(RedirectingOverlay.prototype.componentWillUnmount).toHaveBeenCalledTimes(1)
  })

また使用:

  • "enzyme": "^3.6.0"
  • "jest": "23.5.0"
  • "enzyme-adapter-react-16": "^1.5.0"
2
Wallysson Nunes