Reactjs 如何使用酶(Jest)测试React原生单元测试中的元素值

Reactjs 如何使用酶(Jest)测试React原生单元测试中的元素值,reactjs,react-native,jestjs,enzyme,Reactjs,React Native,Jestjs,Enzyme,我有以下Flash.js组件要测试 export default class SnapshotChild extends Component { render() { return ( <View> <Text>First Text</Text> <Text>Second Text</Text> </View> ); }} 导

我有以下Flash.js组件要测试

export default class SnapshotChild extends Component {

render() {
    return (
        <View>
            <Text>First Text</Text>
            <Text>Second Text</Text>
        </View>
    );
}}
导出默认类SnapshotChild扩展组件{
render(){
返回(
第一个文本
第二文本
);
}}
我的测试用例是

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');
      })});
description('Flash Card',()=>{
常数闪光=浅();
它('测试``值',()=>{
log(flash.debug());
expect(flash.find('Component Text').at(0.Text()).toEqual('First Text');
})});
现在,当我使用npm test运行这段代码时,结果显示出来了

Expected value to equal:
  "First Text"
Received:
  "<Text />"
期望值等于:
“第一个文本”
收到:
""
我的预期结果是“第一个文本”,并获得“文本标记”
怎么了,请有人帮我一下。提前感谢。

因为您使用了
shallow()
嵌套
不会被渲染。所以方法
.text()
不知道文本的外观。所以它似乎只是返回元素名,即使没有所有的道具

当然你可以用
mount()
替换
shallow()
,但是我建议你在这里

那么你的测试看起来像

  const flash = shallow(<Flash />);

  it('has valid default output',()=>{
   expect(flash).toMatchSnapshot();
  })});
Ezyme的助手
.text()
如何知道在没有渲染节点的情况下返回什么

[UPD2]如果无法使用
toMatchSnapshot()
仍然可以直接测试
道具

expect(flash.find(Text).at(0).props().children).toEqual('First Text')

但是
toMatchSnapshot
在几个方面(可读性、可维护性、灵活性和其他*能力)要好得多

    import { configure } from 'enzyme'import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
在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();
    });
});
从'enzyme'导入{shall}从'../App'导入App;
从“React”中导入React描述('测试登录模块',()=>{
常量appWrapper=浅(


您可以参考

Hi@skyboyer,非常感谢您的快速响应。事实上,我有一项任务要用元素值进行测试。如何在不使用toMatchSnapshot()的情况下完成这项任务,就像使用任何其他道具一样:
expect(flash.find(Text).at(0).props().children.toEqual('First Text')
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();
    });
});