The*_*oul 10 act react-native use-effect react-native-testing-library
我正在react-native-testing-library用来测试我的 react-native 组件。我有一个组件(为了这篇文章,它已经被过度简化了):
export const ComponentUnderTest = () => {
useEffect(() => {
__make_api_call_here_then_update_state__
}, [])
return (
<View>
__content__goes__here
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
这是我的(简化版)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(...);
})
Run Code Online (Sandbox Code Playgroud)
现在,当我运行此代码时,出现此错误:
Can't access .root on unmounted test renderer
我什至不知道这个错误消息是什么意思。我遵循了react-native-testing-library有关如何使用act and useEffect.
任何帮助将不胜感激。谢谢
小智 5
我找到了一个解决方法:
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(...);
})
Run Code Online (Sandbox Code Playgroud)
您可以使用:@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);
});
});
Run Code Online (Sandbox Code Playgroud)
也应该与 useEffect 一起使用,但我自己还没有测试过。与 useState 配合使用效果良好。
root = render(<ComponentUnderTest />);
Run Code Online (Sandbox Code Playgroud)
应该
root = create(<ComponentUnderTest />);
Run Code Online (Sandbox Code Playgroud)
----完整代码片段。上述更改后它对我有用
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 />)
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4882 次 |
| 最近记录: |