react-native-testing-library icon indicating copy to clipboard operation
react-native-testing-library copied to clipboard

"Cannot read property 'target' of undefined" with fireEvent.press()

Open defless opened this issue 6 years ago • 5 comments

Ask your question

During a test that I've made over one of my component, I wanted to 'click' on a Button . This button worked perfectly out of the test. But wen the button is trigger by fireEvent.press() it seems to not recognise the event and so the target of it.

I'm a beginner in testing and moreover in react-native tests so it's quite possible that this issue is due to me. But if someone got an idea it would be very appreciable 👍

The Button

<Button
  testID="mainButton"
  title="Découvrir les offres"
  style={defaultStyles.p3_actions}
  color="#000A24"
  onPress={(e) => {
    Linking.openURL(data.config.subscription_url);
    onSubscribeClick(
      widget,
      e.target,
      data.config.subscription_url
    );
  }}
/>

The Test

it('should render without issues', () => {

    const { getByTestId } = render(
      <PaywallContext onSubscribeClick={(a, b, c) => {}} >
        <SubscriptionWidget { ... widgetProps }/>
      </PaywallContext>
    );

    const element = getByTestId('widgetView');
    const mainButton = getByTestId('mainButton');
    fireEvent.press(mainButton);
    expect(element).toBeDefined();
  });

The Issue

<SubscriptionWidget /> › should render without issues

    TypeError: Cannot read property 'target' of undefined

      37 |           onSubscribeClick(
      38 |             widget,
    > 39 |             e.target,
         |               ^
      40 |             data.config.subscription_url
      41 |           );
      42 |         }}

      at onPress (src/paywall/components/SubscriptionWidget.js:39:15)
      at node_modules/react-native-testing-library/build/fireEvent.js:40:26
      at batchedUpdates (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12463:12)
      at act (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:15367:14)
      at invokeEvent (node_modules/react-native-testing-library/build/fireEvent.js:39:3)
      at Function.press (node_modules/react-native-testing-library/build/fireEvent.js:47:33)
      at Object.<anonymous> (tests/widgets/subscriptionWidget.test.js:38:15)

defless avatar Jun 09 '20 13:06 defless

@defless I am not sure what do you want to achieve in your test.

From the console log I see that the second parameter passed to onSubscribeClick call (e) is undefined, so it throws TypeError when you try to read target property on it.

As a side note, getBy queries are kind of assertions by themselves, they throw if they cannot find element, so const element = getByTestId('widgetView'); already checks that element is rendered. Hence, making later statement expect(element).toBeDefined(); not really checking anything new.

The connection between components is your code is not entire clear from the code sample. Can you provide a sample repo to reproduce your issue?

mdjastrzebski avatar Jun 09 '20 18:06 mdjastrzebski

@mdjastrzebski I didn't know for getBy queries ! I will remove de expect(). .

What I want to achieve in my test , is to check if the component is rendering well. And in order to have a 100% coverage over my code I want to simulate clicks on buttons to tests the attached scripts to my event onPress. It maybe not the right way to do things.

What I wanted to do is to pass the event target to the onSubscribeClick() function. When I press the button on the server it works properly but once it's simulated by a test it seems to not recognise e which is supposed to be the event himself.

Unfortunately I won't be able right now to provide you a sample repo ... But I can give you more sample of my code right now, maybe it will be enough.

Thanks for your answer and your help !

The SubscriptionWidget that i'm testing

import React, { useContext } from 'react';
import {
  View,
  Text,
  Button,
  Linking,
} from 'react-native';
import PropTypes from 'prop-types';
import { AppContext } from '../services/contexts';

import { defaultStyles } from '../theme/styles';

const SubscriptionWidget = ({ data, widget }) => {

  const { onSubscribeClick } = useContext(AppContext);

  return (

    <View
      style={defaultStyles.p3_container}
      testID="widgetView"
    >
      <Text style={defaultStyles.p3_title}>
        Cet article est reservé aux abonnés.
      </Text>
      <Text style={defaultStyles.p3_text}>
        Pour profiter pleinement de l&apos;ensemble de ses articles,
        {'\n'} Test vous propose de découvrir ses offres d&apos;abonnement.
      </Text>
      <Button
        testID="mainButton"
        title="Découvrir les offres"
        style={defaultStyles.p3_actions}
        color="#000A24"
        onPress={(e) => {
          Linking.openURL(data.config.subscription_url);
          onSubscribeClick(
            widget,
            e.target,
            data.config.subscription_url
          );
        }}
      />
      <View style={defaultStyles.p3_subactions_container}>
        <Text
          testID="loginButton"
          style={defaultStyles.p3_subaction}
          onPress={() => Linking.openURL(data.config.login_url)}>
          Je me connecte
        </Text>
      </View>
    </View>

  );
};

SubscriptionWidget.propTypes = {
  data: PropTypes.object,
  widget: PropTypes.string,
};

SubscriptionWidget.displayName = 'SubscriptionWidget';

export default SubscriptionWidget;

My test file

import React from 'react';

import { render, fireEvent } from 'react-native-testing-library';

import SubscriptionWidget from '../../src/paywall/components/SubscriptionWidget';
import PaywallContext from '../../src/paywall/components/PaywallContext';

const widgetProps = {
  data: {
    config: {
      login_url: 'google.com',
      subscription_url: 'google.com',
    },
    styles: {
      button_color: '#FFFFFF',
      brand_logo: 'https://image.flaticon.com/icons/svg/3039/3039343.svg',
    },
    texts: {
      gift_desc: 'test description',
    },
  },
};

describe('<SubscriptionWidget />', () => {

  it('should render without issues', () => {

    const { getByTestId } = render(
      <PaywallContext onSubscribeClick={(a, b, c) => {}} >
        <SubscriptionWidget { ... widgetProps }/>
      </PaywallContext>
    );

    const element = getByTestId('widgetView');
    const loginButton = getByTestId('loginButton');
    const mainButton = getByTestId('mainButton');
    fireEvent.press(loginButton);
    fireEvent.press(mainButton);
  });

});

My PaywallContext component

import React, { useState } from 'react';
import { AppContext } from '../services/contexts';

const PaywallContext = ({
  children,
  onLock,
  onRelease,
  onSubscribeClick,
  onLoginClick,
}) => {

  const [active, setActive] = useState(true);

  return (
    <AppContext.Provider
      value={{
        setActive: setActive,
        active: active,
        onLock: onLock,
        onRelease: onRelease,
        onSubscribeClick: onSubscribeClick,
        onLoginClick: onLoginClick,
      }}>
      {children}
    </AppContext.Provider >
  );
};

export default PaywallContext;

defless avatar Jun 10 '20 08:06 defless

I've done a sample test how does onPress work.

In running RN app the onPress handler receives event with event.target being a number.

In RNTL test onPress handler receives undefined event. Which is technically correct according to flow types for RN Button component.

@defless How do you use this value event.target? If for identifying button, then maybe you could use closure to capture some button identifier in event handler.

mdjastrzebski avatar Jun 10 '20 21:06 mdjastrzebski

Yeah that's exactly what I want to do with it. I want to be able to identify which button is pressed.

Capture d’écran 2020-06-11 à 14 28 00

maybe you could use closure to capture some button identifier in event handler.

Then that's what I'm going to look into ! Thank for your help @mdjastrzebski .

defless avatar Jun 11 '20 12:06 defless

Just to clarify by what I mean by passing button identifier in closure:

onPress={() => { // <-- here: could remove unused 'e' parameter
          Linking.openURL(data.config.subscription_url);
          onSubscribeClick(
            widget,
           "button 1", // <-- here: used string identifier instead of 'e.target':
            data.config.subscription_url
          );
        }}

mdjastrzebski avatar Jun 12 '20 06:06 mdjastrzebski