Testing TextInput Component in react-native

后端 未结 3 1364
感情败类
感情败类 2021-01-19 06:26

I have some problems with testing TextInput changes in react-native with jest and enzyme.

My component that handles user input basi

3条回答
  •  余生分开走
    2021-01-19 07:05

    You can add and testID in your TextInput Field and accessibilityLabel as one of the props, add both for ios and android compatibility, Here is the TextInput code.

       
             
    

    In your test file do a shallow rendering, here

        describe('Your component', () => {
         it('Component: renders correctly', () => {
         const tree = renderer.create().toJSON();
         expect(tree).toMatchSnapshot();
      });
      it('Has  TextInput', () => {
       const tree2 = renderer.create().toJSON();
       expect(findElement(tree2, '#email')).toBeDefined();
     });
    
    });
    

    Then define the function findElement above describe. With console.warn you should see your props of TextInput and in that your testID

       const findElement = function (tree2, element) {
       let result = undefined
       console.warn(tree2.children)
       for(node in tree2.children){
       if(tree2.children[node].props.testID = element) {
       result = true
       }
      }
       return result
     }
    

    It will test for all available TextInputs .... Note: Shallow rendering will only work if the TextInput is only one level deep(Inside one view only) if it is nested refer here - https://medium.com/@AidThompsin/heres-how-you-unit-test-textinput-with-react-native-63e1f7692b17

提交回复
热议问题