Search code examples
javascriptreact-nativemocha.jsreact-test-rendererreact-native-vector-icons

react-native-vector-icons + mocha: Invariant Violation


This is my Component. It runs without problems on emulator/phone:

// mycomponent.js
import React, {Component} from 'react';
import {View} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

export class MyComponent extends Component {
    // ...
    render () {
        return (
            <View>
               <Icon
                   name="check"
                   size={25}
                   color={'#62B300'}
               />
            </View>
        )
    }
}

But when I run the unit test in this file (mocha --recursive test/**/*.js):

// mycomponent.spec.js
import chai from 'chai';
import TestRenderer from 'react-test-renderer';
import mock from 'mock-require';
import 'react-native-mock-render/mock';
import {MyComponent} from '../app/components/MyComponent';

mock('react-native-vector-icons/FontAwesome', {});


describe('MyComponent', () => {
    it('should render', () => {
       const mycomponent = TestRenderer.create(<MyComponent>);

       return expect(mycomponent.root).to.exist;
    }
}

It throws:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up defau lt and named imports.

Check the render method of MyComponent.

It works if I use a <View> instead of the <Icon> but it should be mocked. How can I fix this?


Solution

  • Solved it. To make this work, the mock needs to return a function returning null instead of an Object.

    mock('react-native-vector-icons/FontAwesome', () => null);