Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Picker and Picker.Item with jest in React-Native?

I am trying to snapshot test this snippet of code:

import React, { Component } from 'react';
import {
  Picker,
} from 'react-native';

export default class TestComponent extends Component {

  render() {
    return (
      <Picker
        selectedValue={this.props.asset.type}
        onValueChange={this.props.onTypeChange}>
        <Picker.Item label="Type of asset" value="default" />
        <Picker.Item label="Car" value="car" />
        <Picker.Item label="Boat" value="boat" />
        <Picker.Item label="Ship" value="ship" />
      </Picker>
    );
  }
}

My test looks like this right now:

import 'react-native';
import React from 'react';
import TestComponent from './TestComponent';

import renderer from 'react-test-renderer';

describe('TestComponent', () => {
  const asset = {
    type: 'car',
  }
  it('renders correctly', () => {
    const tree = renderer.create(
      <TestComponent 
        asset={asset} />
    ).toJSON();
    expect(tree).toMatchSnapshot();
  });
})

My problem is that I get:

TypeError: Cannot read property '_tag' of undefined

I think that I should mock it based on this issue

I have tried adding simply:

jest.mock('Picker', () => 'Picker')

But than it still throws an error because Picker.Item is still not mocked

Invariant Violation: Element type is invalid: expected a string (for built-
in components) or a class/function (for composite components) 
but got: undefined. Check the render method of `TestComponent`.

Other variants I tried with no avail:

jest.mock('Picker', () => {return {Item: 'Item'}});
----------------------------------------------------
class Picker{
  Item = 'PickerItem'
}
jest.mock('Picker', () => {
  return Picker;
});
like image 850
Milan Gulyas Avatar asked Aug 31 '25 18:08

Milan Gulyas


1 Answers

Created a github issue as well and here is a working answer:

jest.mock('Picker', () => {
  const Picker = class extends Component {
    static Item = props => React.createElement('Item', props, props.children);
    static propTypes = { children: React.PropTypes.any };

    render() {
      return React.createElement('Picker', this.props, this.props.children);
    }
  }
  return Picker;
})
like image 72
Milan Gulyas Avatar answered Sep 03 '25 04:09

Milan Gulyas