Home > Software engineering >  How to test image source in react native
How to test image source in react native

Time:01-10

my test result is number 1 instead of the name of the icon. Do you know how can I test the image source?

Code:

<Image
    source={buttonVisibility ? arrowRight : arrowDown}
    style={{ width: 20, height: 20 }}
    testID="image-source"
/>       

My test:

  it('icon should be arrowRight', () => {
    const wrapper = shallow(<DetailsPageLastPosition bike={bike} buttonVisibility={true} />);
    expect(wrapper.find({ testID: 'image-source' }).props().source).toEqual('arrowRight');
  });

Test result:

● DetailsPageLastPosition component › icon should be arrowRight

   expect(received).toEqual(expected) // deep equality

   Expected: "arrowRight"
   Received: 1

      73 |   it('icon should be arrowRight', () => {
      74 |     const wrapper = shallow(<DetailsPageLastPosition bike={bike} buttonVisibility={true} />);
    > 75 |     expect(wrapper.find({ testID: 'image-source' }).props().source).toEqual('arrowRight');
         |                                                                     ^
      76 |   });
      77 | });
      78 |

CodePudding user response:

Local image assets always resolve to a number (see here in the docs). One easy way around this would be to dynamically assign a test ID based on your conditional.

<Image
    source={buttonVisibility ? arrowRight : arrowDown}
    style={{ width: 20, height: 20 }}
    testID={`image-source-${buttonVisibilty ? 'arrowRight' : 'arrowDown'}`}
/> 

// in test

expect(wrapper.find({ testID: 'image-source-arrowRight' }) // etc
  • Related