2017-08-23 41 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(); 
    }); 
});