React Native Test Component With Moti and Jest error:SyntaxError:Unexpected token 'export'

ou6hu8tu  于 9个月前  发布在  Jest
关注(0)|答案(2)|浏览(108)

我正在尝试测试一个用moti库创建的组件,但是当我运行测试时,显示了错误。Moti文档没有显示任何关于如何正确模拟组件的内容。
({“Object.":function(module,exports,require,__dirname,__filename,jest){export * from '@motify/core';^

SyntaxError: Unexpected token 'export'

      1 | import {View, TouchableOpacity, Text, FlatList, Pressable} from 'react-native';
    > 2 | import {AnimatePresence, MotiView} from "moti";
        | ^
      3 | import React from "react";
      4 | import {WLText} from "##ui/components/elements/wl-text";
      5 | import {styles} from './wl-autocomplete-suggestion.style';

字符串
我的组件

import {View, TouchableOpacity, Text, FlatList, Pressable} from 'react-native';
import {AnimatePresence, MotiView} from "moti";
import React from "react";
import {WLText} from "##ui/components/elements/wl-text";
import {styles} from './wl-autocomplete-suggestion.style';
import PropTypes from "prop-types";
import _ from 'lodash';

export const WlAutocompleteSuggestionsComponent = (props) => {

  const {showSugestions, data, onPress, onPressItem, searchText, categories} = props
  const {suggestions, brands,} = data || []

  const highLightWord = (word, highlight) => {
    const match = _.words(word?.toLowerCase(), RegExp(highlight?.toLowerCase()));
    const notMatch = _.replace(word.toLowerCase(), match, "");
    return (
      <View style={{flexDirection: "row"}}>
        <WLText style={{fontWeight: 'bold'}} text={match}/>
        <WLText text={notMatch}/>
      </View>
    );
  };

  return (
    <AnimatePresence>
      {showSugestions && suggestions.length > 0 &&
          <MotiView
              from={{
                opacity: 0.5,
              }}
              animate={{
                opacity: 1
              }}

              transition={{
                type:"timing",
                duration: 300,
              }}
              exit={{
                opacity: 0.5,
              }}

              style={styles.container}>
              <Pressable
                  onPress={onPress}
                  style={styles.backgroundSylte}/>
              <View
                  style={styles.contentWrapper}>
                  <TouchableOpacity onPress={() => onPressItem(suggestions[0])}>
                    {highLightWord(suggestions[0], searchText)}
                  </TouchableOpacity>
                  <View style={styles.brandsContainer}>
                      <View style={styles.brandsWrapper}>
                          <View
                              style={styles.brandsTagsWrapper}>
                            {categories?.map((item) => <View
                              key={item.name}
                              onTouchEnd={(e) => {
                                e.stopPropagation()
                              }}>
                              <TouchableOpacity
                                onPress={() => {
                                  onPressItem(item.name)
                                }}
                                style={styles.tagContainer}>
                                <WLText style={{fontStyle: 'oblique'}} text={'In '}/>
                                <WLText text={`${item.name}`}
                                        styleName={'NORMAL_MULTILINE'} ellipsizeAtLine={2} testID={`_TITLE`}/>
                              </TouchableOpacity>
                            </View>)}

                            {brands.map((item) => <View
                              key={item}
                              onTouchEnd={(e) => {
                                e.stopPropagation()
                              }}>
                              <TouchableOpacity
                                onPress={() => {
                                  onPressItem(item)
                                }}
                                style={styles.tagContainer}>
                                <WLText text={item}
                                        styleName={'NORMAL_MULTILINE'} ellipsizeAtLine={2} testID={`_TITLE`}/>
                              </TouchableOpacity>
                            </View>)}
                          </View>
                      </View>
                  </View>
                  <View>
                    {suggestions.length > 0 &&
                        <View style={{justifyContent: 'center',}}>
                          {suggestions.slice(1).map((item) => <View
                            key={item}
                            onTouchEnd={(e) => {
                              e.stopPropagation()
                            }}>
                            <TouchableOpacity
                              onPress={() => {
                                onPressItem(item)
                              }}
                              style={styles.itemStyle}>
                              {highLightWord(item, searchText)}
                            </TouchableOpacity>
                          </View>)}
                        </View>
                    }
                  </View>
              </View>
          </MotiView>
      }
    </AnimatePresence>
  )
}

WlAutocompleteSuggestionsComponent.propTypes = {
  showSugestions: PropTypes.bool,
  searchText: PropTypes.string,
  data: PropTypes.object,
  onPressItem: PropTypes.func,
  onPress: PropTypes.func,
  categories: PropTypes.array
};


测试代码

import {render} from "@testing-library/react-native";
import React from "react";
import {
  WlAutocompleteSuggestionsComponent
} from "../wl-autocomplete-suggestions-component";

describe('WLAutocompleteSuggestions', ()=>{
  it('Renders Properly', ()=>{
    const {  getByTestId } = render(<WlAutocompleteSuggestionsComponent />);
    const titleText = getByTestId('_TITLE');
    expect(titleText).toBeTruthy()

  })
})

70gysomp

70gysomp1#

尝试将moti/.*添加到jest配置中的transformIgnorePatterns字段(jest.config.js文件或package.json中的jest属性),因此结果应该如下所示:
transformIgnorePatterns: ['node_modules/(?!(jest-)?@?react-native|moti/.*)']

3z6pesqy

3z6pesqy2#

谢谢@arseniy它工作!
下面是我的配置jest.config.js,如果人们使用TypeScript和Tamagui

// usefull to share ts config with `import { Stuff } from "@/components/Stuff";`
const { pathsToModuleNameMapper } = require("ts-jest");
const { compilerOptions } = require("./tsconfig");

// extract to an array to make it human readable
const packagesToTransform = [
  "react-native",
  "react-native-(.*)",
  "@react-native",
  "@react-native-community",
  "@react-navigation",
  "expo",
  "expo-(.*)",
  "react-native-svg",
  "@sentry/.*",
  "moti/.*"
];

/**
 * @type {import('@jest/types').Config.InitialOptions}
 * */
const config = {
  preset: "jest-expo",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
  modulePaths: ["<rootDir>/"],
  transformIgnorePatterns: [
    `node_modules/(?!(${packagesToTransform.join("|")})/)`
  ]
};

module.exports = config;

字符串

相关问题