radarlabs / radar-sdk-js

Web JavaScript SDK for Radar, the leading geofencing and location tracking platform
https://radar.com
Apache License 2.0
42 stars 11 forks source link

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

Closed brennanbutler01 closed 11 months ago

brennanbutler01 commented 1 year ago

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 commented 1 year ago

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 commented 11 months ago

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.

https://github.com/radarlabs/radar-sdk-js/pull/129

brennanbutler01 commented 11 months ago

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