我正在使用react-native-testing-library
测试我的本机组件。
我有一个组件(出于这篇文章的目的,它已经过简化):
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
进行测试。
任何帮助将不胜感激。谢谢
答案 0 :(得分:2)
我找到了一种解决方法:
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(...);
})
答案 1 :(得分:1)
以下步骤解决了我的情况:
将React
和react-test-renderer
版本升级到16.9或更高版本,以支持async
内部的act
功能(两个软件包都必须与i相同版本知道)
按照@helloworld的建议,将react-native-testing-library
的{{1}}替换为render
的{{1}}(谢谢您,先生,它对我有帮助)
使测试功能react-test-renderer
在create
之前带有async
,并向其传递act
函数
最终结果看起来像这样:
await
答案 2 :(得分:1)
您可以使用:@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 一起工作正常。
答案 3 :(得分:0)
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 />)
})
})