shichongrui / react-native-test-utils

A test utils library for testing react native components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Does not Find TouchableOpacity

k-gregor opened this issue · comments

When I test
listViewScreen.queryAll("TouchableOpacity")[0].simulate('press', {});

I get
TypeError: Cannot read property 'simulate' of undefined

But it does find an Image that is wrapped by the Touchable Opacity like so:

<TouchableOpacity onPress={() => whatever()}>
    <Image source={{uri: "someuri" }}/>
</TouchableOpacity>

Any ideas on this?

Thanks in advance!

Try putting

jest.mock('TouchableOpacity', () => 'TouchableOpacity')

at the top of your test file. Because we are using toJSON at the moment we only get the final rendered tree so because TouchableOpacity is not what actually gets rendered it can't find it.

Thanks a lot, mate! That did the trick.
I would have liked to create a pull request including a note on that into your documentation, however I don't really know which React components are rendered as they are and which not. E.g. 'Text' works fine, 'TouchableOpacity' does not, and I don't know why that is the case and for which components.

As far as I know all the Touchable* components have this behavior. I would welcome a PR outlining those components and perhaps a note saying that if you run into a problem of not being able to find the component being rendered that you might need to mock it.

Hello, this might help:

There is one things though: if the Button (which below the scene is a Touchable) or a Switch have the disabled property true the onPress still executes.

import 'react-native';
import mockComponent from 'react-native/jest/mockComponent'; // <-- ADD THIS
import React from 'react';
import renderer from 'react-native-test-utils';

import App from '../App';

jest.mock('Button', () => {  //<-- ADD THIS
    return mockComponent('Button');
});

it('renders correctly', () => {
    const tree = renderer(<App />);
    expect(tree.toJSON()).toMatchSnapshot();
});

it('changes text onPress', () => {
    const tree = renderer(<App />);
    const btn = tree.query('#theButton');

    btn.simulate('press'); //<-- NOW YOU CAN SIMULATE
    expect(tree.state().active).toBe(true);
    expect(tree.query('#theText').text()).toBe('Active');

    btn.simulate('press');
    expect(tree.state().active).toBe(false);
    expect(tree.query('#theText').text()).toBe('Dead');
});

@shichongrui I could make a PR with this stuff added to docs if you think it's good enough 😊

It seems that we should probably add a check to the simulate method to not call the handler in the case of being disabled. Things such as onPress and onChange might be good events to ignore if the element is disabled.

Fixed in #13