1

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?

sAm_vdP
  • 331
  • 2
  • 7

2 Answers2

1

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.

acharlop
  • 309
  • 4
  • 12
0

Stateless components don't support refs, create a stateful component.

For more detail see this answer

Harsh Vardhan
  • 111
  • 1
  • 14
  • 1
    Switch is an component provided by react native, I'm afraid I cannot make that stateful. Besides, the warning only pops up in jest. – sAm_vdP Nov 02 '17 at 05:54