[英]How to test a function inside react component?
I have a component that renders tiles and arranges based on the configuration from our configuration server.我有一个组件,它根据我们的配置服务器的配置呈现瓷砖和排列。 I have two functions one useEffect hook to render tiles and fetchConfig() to fetches configuration from external server, my question is how can we write testcases for a function that is inside a component?
我有两个函数,一个是 useEffect 钩子来渲染图块,另一个是 fetchConfig() 从外部服务器获取配置,我的问题是我们如何为组件内的 function 编写测试用例?
StyleWrapper.tsx
StyleWrapper.tsx
let fetchConfig = () => {
await fetch(HOST+"/config/style", {
method: "GET",
body: new URLSearchParams(reqParams),
}).then(async (response) => {
const styleConfigData = await response.json();
return styleConfigData;
});
};
const StyleWrapper = (props) => {
useEffect(() => {
async function arrangeTiles() {
// Arrange Tile logic
return "Tile Arranged"
}
arrangeTiles();
});
return (
<Context.Provider value={{ arrangeTiles }}>
<div id="cnplStyleContainer">{props.children}</div>
</Context.Provider>
);
};
export default StyleWrapper;
I think that you're asking, "how can I test a nested function?"我认为您在问,“我如何测试嵌套的 function?” The answer is that you can't.
答案是你不能。 The better approach is this: If the function is relatively simple, you should be able to write a satisfying unit test for the function that contains it.
更好的方法是:如果 function 相对简单,您应该能够为包含它的 function 编写令人满意的单元测试。 If it truly needs to be tested on its own, then make it an exportable function and test it appropriately using eg Jest .
如果确实需要自行测试,则将其设为可导出的 function 并使用例如Jest对其进行适当测试。
Additionally, if you're interested in testing fetchConfig
, I would recommend that you look into mocking .此外,如果您有兴趣测试
fetchConfig
,我建议您查看mocking 。 Unless you're writing an end-to-end test , it's generally inadvisable to rely on network resources in a test scenario.除非您正在编写端到端测试,否则通常不建议在测试场景中依赖网络资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.