react-native-vector-icons + mocha:不变违规
react-native-vector-icons + mocha: Invariant Violation
这是我的组件。它 运行s 在 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>
)
}
}
但是当我运行这个文件中的单元测试时(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;
}
}
它抛出:
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
.
如果我使用 <View>
而不是 <Icon>
它会起作用,但它应该被嘲笑。
我该如何解决这个问题?
解决了。为了使这项工作,模拟需要 return 函数 returning null
而不是对象。
mock('react-native-vector-icons/FontAwesome', () => null);
这是我的组件。它 运行s 在 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>
)
}
}
但是当我运行这个文件中的单元测试时(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;
}
}
它抛出:
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
.
如果我使用 <View>
而不是 <Icon>
它会起作用,但它应该被嘲笑。
我该如何解决这个问题?
解决了。为了使这项工作,模拟需要 return 函数 returning null
而不是对象。
mock('react-native-vector-icons/FontAwesome', () => null);