henninghall / react-native-date-picker

React Native Date Picker is datetime picker for Android and iOS. It includes date, time and datetime picker modes. The datepicker is customizable and is supporting different languages. It's written with native code to achieve the best possible look, feel and performance.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot import DatePicker into tests (vitest)

ranger-ross opened this issue · comments

commented

Describe the bug
I cannot import the date picker component when writing unit tests with vitest.

Getting the following error

SyntaxError: Cannot use import statement outside a module

Module ...../node_modules/react-native-date-picker/src/index.js:1 seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package "react-native-date-picker" asking them to ship the file in .mjs extension or add "type": "module" in their package.json.

As a temporary workaround you can try to inline the package by updating your config:

// vitest.config.js
export default {
  test: {
    server: {
      deps: {
        inline: [
          "react-native-date-picker"
        ]
      }
    }
  }
}

If I try adding the recommended config in the error, the error changes to

Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
 ❯ formatError node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:61716:46
 ❯ TransformContext.error node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:61710:19
 ❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:59945:22
 ❯ Object.transform node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:62011:30
 ❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:47793:29

Expected behavior
When importing the DatePicker in vitest test, it should import properly

To Reproduce

// vitest.config.ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react';
import reactNative from 'vitest-react-native';

export default defineConfig({
    plugins: [
        reactNative(),
        react()
    ]
})
// example.spec.tsx
import 'react-native';
import { test, expect } from "vitest";
import * as renderer from "@testing-library/react-native";
import DatePicker from 'react-native-date-picker';

test("DatePicker should render", () => {
    const view = renderer.render(
        <DatePicker
            modal
            open={true}
            date={new Date()}
        />
    );
    expect(view).not.toBeNull()
});

Smartphone (please complete the following information):

  • OS: n/a
  • React Native version: 0.72.6
  • react-native-date-picker version: 4.3.3
  • vitest: 0.34.6
  • vitest-react-native: 0.1.4
  • @vitejs/plugin-react: 4.2.0

P.S. Thank you for providing this library. It is a lifesaver.