![](/img/trans.png)
[英]How to test/mock a fetch api in a React Component using Jest?
[英]React: How mock functions and test component rendering with jest:
我很新來的反應/開玩笑。 我試圖測試一個非常簡單的react組件,該組件從服務器獲取數據並呈現響應。 我的組件如下所示:
export default class myComponent extends Component {
constructor(props) {
super(props);
}
async componentDidMount() {
try {
let response = await axios.get(`server/url/endpoint`);
this._processSuccess(response.data);
} catch(e) {
this._processFail(e);
}
}
_processSuccess(response) {
this.setState({pageTitle: response.data.title, text: response.data.text});
}
render() {
return (
<div className="title">{this.state.pageTitle}</div>
);
}
}
現在,我想測試這個課程。 當我測試時:
我嘗試了如下所示的方法:
import React from 'react'
import MyComponent from './MyComponent'
import renderer from 'react-test-renderer'
import { shallow, mount } from 'enzyme'
describe('MyComponent', () => {
it('should display proper title', () => {
const c = shallow(<MyComponent />);
c._processSuccess(
{data:{pageTitle:'siteName', test:'text'}}
);
// couldn't go further as Im getting error from the above line
});
});
但是,我正在獲取MyComponent._processSuccess不是函數錯誤。 這樣做的正確方法是什么?
shallow()
返回一個帶有一些utils方法的酶包裝器 ,以測試渲染的組件。 它不會返回組件實例。 這就是為什么在調用c._processSucces()
時收到錯誤的原因。 要訪問該組件,可以在包裝器上使用.instance()
方法 ,因此以下各項應適用:
const c = shallow(<MyComponent />);
c.instance()._processSuccess(
{data:{pageTitle:'siteName', test:'text'}}
);
為了避免調用該組件的componentDidMount()
,可以嘗試在淺層渲染器上設置disableLifecycleMethods
,但是我不確定,因為此處酶的文檔不是100%清晰的:
const c = shallow(<MyComponent />, {
disableLifecycleMethods: true
});
最后,您可以使用Enzyme的contains()
和Jest斷言方法之一來檢查輸出是否包含預期的<div>
:
expect(c.contains(<div className="title" />)).toBe(true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.