1

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?

4

1 回答 1

1

解决了。为了使这个工作,模拟需要返回一个函数null而不是一个对象。

mock('react-native-vector-icons/FontAwesome', () => null);
于 2018-12-17T17:28:18.963 回答