我正在尝试围绕React Native测试获得一些基本的理解,包括enzyme和react-native-mock .
不包括在下面:用于mocha的自定义编译器以获得babel善良 .
我的代码如下:
Block.jsx
:
import React from 'react';
import {View} from 'react-native';
export default ({title, ui}) => (
<View>
Title: {title}
</View>
);
Block.test.js
import { shallow } from 'enzyme';
import { expect } from 'chai';
import {Block} from '../';
import React from 'react';
describe('<Block /> with props: title', () => {
it('should have correct props', () => {
expect(
shallow(<Block title="Something" />).props()
).to.deep.equal( {title:"Something"} );
});
it('should have correct title', () => {
expect(
shallow(<Block title="Something" />).text()
).to.equal( "Something" );
});
});
测试结果
摩卡命令:
mocha --compilers js:./test/support/compiler.js --require react-native-mock/mock --recursive **/test/*.test.js --watch
摩卡测试结果:
<Block /> with props: title
1) should have correct props
2) should have correct title
2 failing
1) <Block /> with props: title should have correct props <Text />:
AssertionError: expected { Object (children) } to equal { title: 'Something' }
+ expected - actual
{
- "children": [
- "Title: "
- "Something"
- ]
+ "title": "Something"
}
at Context.<anonymous> (components/test/Block.test.js:24:120)
2) <Block /> with props: title should have correct title <Text />:
AssertionError: expected '<View />' to equal 'Something'
+ expected - actual
-<View />
+Something
at Context.<anonymous> (components/test/Block.test.js:28:119)
意外行为
-
props()
似乎获得了正确的值,但格式与api描述的格式不同 -
text()
不会渲染节点textContent
,而是字符串化标记“<View />
”
替代:道具() . 儿童
给定组件:
import React from 'react';
import {View, Text} from 'react-native';
export default ({title, ui}) => (
<View>
<Text> The title...</Text>
{title}
</View>
);
props().children
是数组 [<Text component instance>, "Something"]
所以跟随测试通过:
it('should have correct props', () => {
expect(
shallow(<Block title="Something" />).props().children
).to.contain( "Something" );
});
问题
为什么Enzyme API的行为与文档中描述的不同?
具体看文档 shallow(<Block title="Something" />).text()
应该等于: The title...Something
我做错了什么,还是我正在使用的技术?
编辑1:其他问题
html()
, render()
, update()
似乎也无法使用我的设置
EDIT: React native only works with shallow at the moment
3 回答
解决方案1:textContent的解决方案
来自Enzyme示例应用程序:
解决方案2:更具语义性
好的,上面的 Alternative: props().children 的语义版本更多 . 这个Github discussion也有所帮助 .
Block.js
:Block.test.js
:expect( shallow(<Block title="Something" />).prop('title') ).to.equal( "Something" );
<View>
标记另一个解决方案(非常类似于
props().children
)是访问道具中的孩子