2017-08-23 56 views
0

我試圖用jest和酶測試我的React組件。我有一個使用react-skylight組件的表單組件。我在表單提交上觸發.show()函數,並在服務器響應成功時觸發。Spying on React子組件方法

我的測試是目前這樣的:

import MyForm from './MyForm'; 
import Popup from 'react-skylight'; 

describe('<MyForm />',() => { 
    it('should show popup on success',() => { 
     const popupShowSpy = jest.spyOn(Popup.prototype, 'show'); 
     const myForm = mount(<MyForm />); 
     myForm.update(); 

     myForm.find('form').simulate('submit'); 
     expect(popupShowSpy).toHaveBeenCalled(); 
    }); 
}); 

但是當我運行測試,我得到了一個錯誤:

expect(jest.fn()).toHaveBeenCalled() 

Expected mock function to have been called. 

我發現here也談類似的問題,但對我來說是不加工。


解決方案:

問題是與axios模塊。它正在更新組件,但反應taht被嘲笑沒有解決,所以感謝這篇文章here,我已經設法編寫測試。而且我將子組件函數調用封裝在父組件自己的函數中,並且探詢了該父函數。

import MyForm from './MyForm'; 
import Popup from 'react-skylight'; 

describe('<MyForm />',() => { 
    it('should show popup on success', async() => { 
     const popupShowSpy = jest.spyOn(MyForm.prototype, 'showPopup'); 
     const myForm = mount(<MyForm />); 

     const response = Promise.resolve({ 
      data: { 
       message: 'Error: some error' 
      }, 
      status: 400 
     }); 
     axios.post = jest.fn(() => response); 
     myForm.find('form').simulate('submit'); 
     await response; 
     myForm.update(); // <- child component is rendered correctly 
     expect(popupShowSpy).toHaveBeenCalled(); 
    }); 
}); 
+1

您可能想重新考慮您的標題。在大多數地方對兒童進行偵查是非法的 – Vaiden

+0

請正式回答並接受您自己的答案。謝謝! –

回答

0

解決方案:

問題是與axios模塊。它正在更新組件,但被嘲笑的響應沒有解決,所以感謝這篇文章here,我已經設法編寫測試。而且我將子組件函數調用封裝在父組件自己的函數中,並且探詢了該父函數。

import MyForm from './MyForm'; 
import Popup from 'react-skylight'; 

describe('<MyForm />',() => { 
    it('should show popup on success', async() => { 
     const popupShowSpy = jest.spyOn(MyForm.prototype, 'showPopup'); 
     const myForm = mount(<MyForm />); 

     const response = Promise.resolve({ 
      data: { 
       message: 'Error: some error' 
      }, 
      status: 400 
     }); 
     axios.post = jest.fn(() => response); 
     myForm.find('form').simulate('submit'); 
     await response; 
     myForm.update(); // <- child component is rendered correctly 
     expect(popupShowSpy).toHaveBeenCalled(); 
    }); 
});