[英]Using react-test-renderer with <Switch> causes "Stateless function components cannot be given refs" warning
I am using react-test-renderer (16.0.0-beta.5) to perform snapshot testing on a custom React Native component.我正在使用 react-test-renderer (16.0.0-beta.5) 在自定义 React Native 组件上执行快照测试。 This component contains a Switch component, which causes this warning to be thrown during test execution:该组件包含一个 Switch 组件,这会导致在测试执行期间抛出此警告:
console.error node_modules\\fbjs\\lib\\warning.js:36 console.error node_modules\\fbjs\\lib\\warning.js:36
Warning: Stateless function components cannot be given refs.警告:不能为无状态函数组件提供引用。 Attempts to access this ref will fail.尝试访问此引用将失败。
Check the render method of
Switch
.检查Switch
的渲染方法。 in Unknown (created by Switch) in Switch在 Switch 中的 Unknown(由 Switch 创建)
Minimal code to reproduce:要重现的最少代码:
import React from 'react';
import renderer from 'react-test-renderer';
import { Switch } from 'react-native';
test('renders correctly', () => {
const tree = renderer.create(
<Switch />
);
});
Some more detail: The issue is caused by the native RCTSwitch component used by Switch.render:更多细节:该问题是由 Switch.render 使用的本机 RCTSwitch 组件引起的:
return (
<RCTSwitch
{...props}
ref={(ref) => { this._rctSwitch = ref; }}
onChange={this._onChange}
/>
);
As you can see this component is assigned a ref.正如你所看到的,这个组件被分配了一个 ref。 However, react-test-renderer uses the following code to check if a component is stateless:然而,react-test-renderer 使用以下代码来检查组件是否是无状态的:
if (typeof value === 'object' && value !== null && typeof value.render === 'function') {
// Proceed under the assumption that this is a class instance
Because RCTSwitch doesn't have a render method, the warning is raised.由于 RCTSwitch 没有渲染方法,因此会引发警告。 Is this a bug?这是一个错误吗?
I added jest.mock('Switch')
to the test and now it passes.我将jest.mock('Switch')
到测试中,现在它通过了。
Note that doing this removes the Switch component from the snapshot, however since there is no reason to test a pure react-native
component I think it's ok as long as all the functions that the Switch uses are tested separately.请注意,这样做会从快照中删除 Switch 组件,但是由于没有理由测试纯react-native
组件,我认为只要 Switch 使用的所有功能都单独测试就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.