1

我正在为我的 React Native 项目编写单元测试。我的主屏幕是 WelcomScreen.js,里面是使用 TouchableOpacity 创建的自定义按钮:

<TouchableOpacity
              testID={'selectEngButton'}
              activeOpacity={0.4}
              onPress={() => onSelectLanguage('en')}>
              <View
                // source={require('../../assets/images/ellipse.png')}
                style={Styles.selectorView}>
                <Image
                  source={require('../../assets/images/us.png')}
                  style={Styles.flagImage}
                />
              </View>
              <Image
                source={
                  activeLanguage === 'en'
                    ? darkMode
                      ? activelangdotdark
                      : activelangdot
                    : darkMode
                    ? inactivelangdotdark
                    : inactivelangdot
                }
                style={Styles.activityDot}
              />
</TouchableOpacity>

以下是称为 onPress 事件的方法:

const onSelectLanguage = (lang) => {
    setActiveLanguage(lang);
    i18n.changeLanguage(lang);
    saveData(APP_LANG, lang);
};

以下是对它的测试:

import React from 'react';
import {Provider} from 'react-redux';
import {act, create} from 'react-test-renderer';
import ConfigureStore from '../src/redux/store';
import WelcomeScreen from '../src/screens/auth/WelcomeScreen';
import {ThemeContextProvider} from '../src/themes/themeProvider';
import {fireEvent, render} from '@testing-library/react-native';

const store = ConfigureStore();

jest.useFakeTimers();

describe('Welcom Screen tests', () => {
  const navigation = {
    navigate: jest.fn(),
  };

  const onSelectLanguage = jest.fn();

  it('select english language', () => {
    const {getByTestId} = render(
      <Provider store={store}>
        <ThemeContextProvider>
          <WelcomeScreen navigation={navigation} />
        </ThemeContextProvider>
      </Provider>,
    );

    const button = getByTestId('selectEngButton');

    console.log('btn002', button);

    fireEvent.press(button);

    expect(onSelectLanguage).toHaveBeenCalled();
  });
});

但它给了我以下错误:

 Welcome Screen tests › select english language

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      45 |     fireEvent.press(button);
      46 |
    > 47 |     expect(onSelectLanguage).toHaveBeenCalled();
         |                              ^
      48 |   });
      49 | });
      50 |

      at Object.<anonymous> (__tests__/WelcomeScreen-test.js:47:30)

我正在遵循官方指南并做完全相同的事情。但它不会在组件上触发 onPress 事件。我做错了什么?

4

0 回答 0