我是单元测试领域的新手,我刚刚开始为我的 React Native (Expo) 应用程序编写测试。经过研究,我终于开始使用Jest 和 React Native Testing Library。
考虑以下使用AppLoading 组件的情况。
const App: React.FC = () => {
const [resourcesHasLoaded, setResourcesHasLoaded] = useState<boolean>(false);
const cacheResources = useCallback(async (): Promise<any> => {
const images = [require('./assets/icon.png')];
const cacheImages = images.map((image) => {
return Asset.fromModule(image).downloadAsync();
});
return Promise.all([cacheImages]);
}, []);
if (resourcesHasLoaded) {
return <Text>Hello world</Text>;
}
return (
<AppLoading
startAsync={cacheResources}
onError={console.warn}
onFinish={() => setResourcesHasLoaded(true)}
/>
);
};
When running my test, that looks like this:
describe('App.tsx', () => {
it('should be able to render', async () => {
render(<App />);
});
});
我最终遇到以下错误(尽管测试通过了):
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
So, I wrapped my `render` in with `act` the following way:
act(() => {
render(<App />);
});
...导致同样的错误。
但是,如果我onFinish
以以下方式将 -callback 包装在我的组件中,则测试通过而不会发出警告。
onFinish={() => act(() => setResourcesHasLoaded(true))}
但是我真的想用特定于测试的函数来污染我的 React 组件吗?我没有看到这方面的例子,所以我只能假设这是不好的做法。
这里有什么建议吗?
更新我在我的评论中得到了@Estus FlaskwaitFor
之后
使用的建议。render
成功了……测试现在通过了。
https://callstack.github.io/react-native-testing-library/docs/api/#waitfor
describe('App.tsx', () => {
it('should be able to render', async () => {
const { findByText } = render(<MyApp />);
await waitFor(() => findByText('Hello world'));
});
});