我正在使用react-native-testing-library测试我的react-native组件。我有一个组件(为了这篇文章的目的,它被过度简化了):
export const ComponentUnderTest = () => {
useEffect(() => {
__make_api_call_here_then_update_state__
}, [])
return (
<View>
__content__goes__here
</View>
)
} 这是我的(简化的) component.spec.tsx
import { render, act } from 'react-native-testing-library';
import { ComponentUnderTest } from './componentundertest.tsx';
test('it updates content on successful call', () => {
let root;
act(() => {
root = render(<ComponentUnderTest />); // this fails with below error message
});
expect(...);
})现在,当我运行这段代码时,我得到了这个错误:Can't access .root on unmounted test renderer

我现在甚至不知道这个错误消息是什么意思。我遵循了react-native-testing-library中关于如何使用act and useEffect进行测试的文档。
任何帮助都将不胜感激。谢谢
发布于 2020-07-21 04:41:45
我找到了一种解决方法:
import { render, waitFor } from 'react-native-testing-library';
import { ComponentUnderTest } from './componentundertest.tsx';
test('it updates content on successful call', async () => {
const root = await waitFor(() =>
render(<ComponentUnderTest />);
);
expect(...);
})发布于 2019-12-04 00:06:46
root = render(<ComponentUnderTest />);应该是
root = create(<ComponentUnderTest />);-完整代码片段。在上面的更改后,它对我来说很有效
import React, { useState, useEffect } from 'react'
import { Text, View } from 'react-native'
import { render, act } from 'react-native-testing-library'
import { create } from 'react-test-renderer'
export const ComponentUnderTest = () => {
useEffect(() => {}, [])
return (
<View>
<Text>Hello</Text>
</View>
)
}
test('it updates content on successful call', () => {
let root
act(() => {
root = create(<ComponentUnderTest />)
})
})发布于 2021-02-26 21:09:12
您可以使用以下命令来实现:@testing-library/react-native
示例:
import { cleanup, fireEvent, render, debug, act} from '@testing-library/react-native'
afterEach(() => cleanup());
test('given correct credentials, gets response token.', async () => {
const { debug, getByPlaceholderText, getByRole } = await render(<Component/>);
await act( async () => {
const emailInput = getByPlaceholderText('Email');;
const passwordInput = getByPlaceholderText('Password');
const submitBtn = getByRole('button', {name: '/submitBtn/i'});
fireEvent.changeText(emailInput, 'email');
fireEvent.changeText(passwordInput, 'password');
fireEvent.press(submitBtn);
});
});应该也可以和useEffect一起使用,但我自己还没有测试过。与useState配合使用效果很好。
https://stackoverflow.com/questions/59131116
复制相似问题