Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4.0.1] - Jest - Cannot find module 'radar-sdk-js' #114

Closed
brennanbutler01 opened this issue Jul 31, 2023 · 3 comments
Closed

[4.0.1] - Jest - Cannot find module 'radar-sdk-js' #114

brennanbutler01 opened this issue Jul 31, 2023 · 3 comments

Comments

@brennanbutler01
Copy link

brennanbutler01 commented Jul 31, 2023

Help Needed configuring jest + Radar

I'm trying to use Radar for autocomplete and address validation, but am running into the following error when running jest:

Test suite failed to run. Cannot find module 'radar-sdk-js' from 'fetchAutocomplete/index.tsx'

In that file, I am importing radar-sdk-js as import Radar from 'radar-sdk-js'

I'm using Next js and my jest config is

// jest.config.js

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/radar/(.*)$': '<rootDir>/radar/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
};

module.exports = createJestConfig(customJestConfig);

I have tried uninstalling and reinstalling Radar. It works fine when I include it as html rather than using yarn.
I tried adding a module name mapper of ^radar-sdk-js': '<rootDir>/node_modules/radar-sdk-js' but that isn't working.

I really like the library and want to keep using it, but I'm not sure how to go about making this work. any help would be appreciated.

Thank you

i'm using jest ^29.5.0

I made some changes to jest config and tried:

onst customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/radar/(.*)$': '<rootDir>/radar/$1',
    '^radar-sdk-js': '<rootDir>/node_modules/radar-sdk-js/dist/radar.js', // Add this otherwise tests will fail. This didn't need to be added before(?)
  },
  transformIgnorePatterns: ['node_modules/(?!(radar-sdk-js)/)'],
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
    '^.+\\.(ts|tsx|mjs)$': 'ts-jest',
  },
  testEnvironment: 'jest-environment-jsdom',
};

This got me a new error:

 Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/brennanbutler/WebstormProjects/mileage/node_modules/radar-sdk-js/dist/radar.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import maplibregl from 'maplibre-gl';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module
@brennanbutler01
Copy link
Author

brennanbutler01 commented Sep 7, 2023

I was able to fix this with vitest by adding the @originjs/vite-plugin-commonjs plugin to my project:

// vitest.config.ts
import { defineConfig } from 'vitest/config';
import path from 'path';
import react from '@vitejs/plugin-react';
import { viteCommonjs } from '@originjs/vite-plugin-commonjs';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    exclude: ['**/node_modules/**', './src/e2e/**', '.next/**'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      lines: 100,
      functions: 100,
      branches: 100,
      statements: 100,
      exclude: ['**/src/yourIgnoredFile.js'],
    },
    setupFiles: ['./vitest.setup.ts'],
    server: {
      deps: {
        inline: ['radar-sdk-js'],
      },
    },
  },
  resolve: {
    alias: {
      '~': path.resolve(__dirname, './src'),
    },
    mainFields: ['module', 'main'],
  },
  plugins: [react(), viteCommonjs({ include: ['radar-sdk-js'] })],
});

Alternatively, things were working when I modified radar-sdk-js package.json to have a main entry like:

// node_modules/radar-sdk-js/package.json
{
  "name": "radar-sdk-js",
  "version": "4.1.6",
  "description": "Web Javascript SDK for Radar, location infrastructure for mobile and web apps.",
  "homepage": "https://radar.com",
  "type": "module",
  "module": "dist/radar.js",
 "main": "dist/radar.js",
...

For this to all work, I needed to make a few extra changes to my vitest.setup.ts to stop errors from being thrown:

// vitest.setup.ts


//https://stackoverflow.com/questions/52968969/jest-url-createobjecturl-is-not-a-function fix for radar
Object.defineProperty(window.URL, 'createObjectURL', { value() {} });

// https://stackoverflow.com/questions/52868727/how-to-mock-window-navigator-language-using-jest fix for radar
Object.defineProperty(window.navigator, 'permissions', {
  writable: true,
  value: { query: vi.fn().mockImplementationOnce(() => Promise.resolve({ state: 'granted' })) },
});

I hope this helps someone

@kochis
Copy link
Collaborator

kochis commented Sep 29, 2023

Hello,

I created a new beta release 4.2.0-beta.0 which adds support for UMD if you want to try and see if that resolves the issue.

#129

@brennanbutler01
Copy link
Author

@kochis my hero.... the beta fixes the test errors. thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants