[英]How do I test the Elements value in React Native unit testing using Enzyme (Jest)
I have the following Flash.js component to Test 我有以下Flash.js组件要测试
export default class SnapshotChild extends Component {
render() {
return (
<View>
<Text>First Text</Text>
<Text>Second Text</Text>
</View>
);
}}
And My test cases is 我的测试用例是
describe('Flash Card', () => {
const flash = shallow(<Flash />);
it('test the `<Text/>` value',()=>{
console.log(flash.debug());
expect(flash.find('Component Text').at(0).text()).toEqual('First Text');
})});
Now when I run this code using npm test the result is showing 现在,当我使用npm test运行此代码时,结果显示
Expected value to equal:
"First Text"
Received:
"<Text />"
My expected result is "First Text" and getting " Text tag ". 我的预期结果是“第一个文本”并获得“ 文本标签 ”。 What's the wrong, please please somebody help me on this.
怎么了,请有人帮我解决这个问题。 Thanks in advance.
提前致谢。
Since you use shallow()
nested <Text />
are not rendered. 由于您使用
shallow()
因此不会呈现嵌套的<Text />
。 So method .text()
does not know how text will look like. 因此,方法
.text()
不知道文本的外观。 So it seems just returning element name even without all its props. 因此,即使没有所有道具,它似乎也只是返回元素名称。
Sure you can replace shallow()
with mount()
but I suggest you using amazing .toMatchSnapshot()
here. 当然,您可以使用
mount()
替换shallow()
,但是我建议您在此处使用令人赞叹的.toMatchSnapshot()
。
Then your tests would look like 然后你的测试看起来像
const flash = shallow(<Flash />);
it('has valid default output',()=>{
expect(flash).toMatchSnapshot();
})});
and that would check for both <Text />
elements and text inside as well. 并且会同时检查
<Text />
元素和内部的文本。
[UPD] additionaly on why .text()
works this way. [UPD]关于
.text()
为什么这样工作的其他信息。 Image you had the same code with slightly different(but equal!) syntax: 图片您具有相同的代码,但语法略有不同(但相等!):
<Text children={'First Text'} />
How could enzyme's helper .text()
know what to return here without rendering node? 酶的助手
.text()
知道不渲染节点就返回什么?
[UPD2] if there is no way to use toMatchSnapshot()
it's still possible to test props
directly: [UPD2]如果无法使用
toMatchSnapshot()
,仍然可以直接测试props
:
expect(flash.find(Text).at(0).props().children).toEqual('First Text')
But toMatchSnapshot
is much better in several ways(readability, maintainability, flexbility and other *abilities) 但是
toMatchSnapshot
在几种方面要好得多(可读性,可维护性,灵活性和其他*功能)
After installing all dependencies,add setup.js 安装所有依赖项后,添加setup.js
import { configure } from 'enzyme'import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
In app.test.js : 在app.test.js中:
import {shallow} from 'enzyme'import App from '../App';
import React from 'react'describe('test login module',()=>{
const appWrapper = shallow(<App/>);
it('renders app module correctly',()=>{
expect(appWrapper).toMatchSnapshot();
});
});
you may refer 你可以参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.