I am using react-test-renderer (16.0.0-beta.5) to perform snapshot testing on a custom React Native component. This component contains a Switch component, which causes this warning to be thrown during test execution:
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
. in Unknown (created by Switch) in 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:
return (
<RCTSwitch
{...props}
ref={(ref) => { this._rctSwitch = ref; }}
onChange={this._onChange}
/>
);
As you can see this component is assigned a ref. However, react-test-renderer uses the following code to check if a component is stateless:
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. Is this a bug?
I added jest.mock('Switch')
to the test and now it passes.
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.
Stateless components don't support refs, create a stateful component.
For more detail see this answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.