2017-02-24 58 views
5

我正在交換從摩卡開玩笑,我想知道是否有方法來窺探反應方法。比如可以說,我有我的組件下面的方法(忽略SDK庫,它只是構建了一個jQuery AJAX調用):Jest spy on functionality

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

使用興農我會通過刺探原型像這樣測試:

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

這將確保代碼覆蓋而不會嘲笑該方法。開玩笑是否有類似的功能?

編輯:此外,如果此功能不存在,測試API調用的下一個最佳策略是什麼?

回答

6

還有就是spyOn方法,即用V19前幾天出臺,已經做了你正在尋找什麼

3

你可以去新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) 
    }); 
})