GithubHelp home page GithubHelp logo

jest-next-dynamic's Introduction

jest-next-dynamic — Formidable, We build the modern web

Maintenance Status

Unlike react-loadable, the dynamic import support offered by Next.js does not expose a way to preload the dynamically imported components in Jest’s environment (which mimics a DOM environment). Even if you get a handle on the Loadable component bundled with Next.js, it skips queuing up the components in DOM-like environments. Bummer!

This module can be imported in your test or setup files to make sure any component created with next/dynamic is added to a queue, which can then be flushed with the exported preloadAll function.

Using this, your component tests (including snapshots) can render the full component tree instead of the loading placeholders.

Setup

In order to transform import() successfully in Jest’s environment, you must use a different transform than the one provided by next/babel (which expects to be built with webpack).

Both of these work fine:

{
  "plugins": ["babel-plugin-dynamic-import-node"]
}

Usage

// This will mock `next/dynamic`, so make sure to import it before any of your
// components.
import preloadAll from "jest-next-dynamic";
// This component can have dynamic imports anywhere in its rendered tree,
// including nested dynamic imports.
import SomeComponent from "./SomeComponent";

beforeAll(async () => {
  await preloadAll();
});

// Your tests here!

Maintenance Status

Experimental: This project is quite new. We're not sure what our ongoing maintenance plan for this project will be. Bug reports, feature requests and pull requests are welcome. If you like this project, let us know!

jest-next-dynamic's People

Contributors

acharyakavita avatar boygirl avatar cpresler avatar exogen avatar ricardo-cantu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-next-dynamic's Issues

Cannot read property 'preload' of undefined when testing with config testEnvironment: 'node' at jest

We are trying to set some SSR tests for our Next.js app to make sure that our server side rendering is working as expected. Some of the requirements of this is that the window object or the document object should be undefined in our environment.

To achieve this we have set our jest test environment to node at the config file jest.config.js:

module.exports = {
   testEnvironment: 'node',
}

We have also set some dynamic imports at our app with the option { ssr: false }, as we want them to be rendered on the client side:

 const DynamicCustomComponent = dynamic(
  () => import('../DynamicCustomComponent'),
  { ssr: false }
);

When having all the above specs we run into the following issue:

 TypeError: Cannot read property 'preload' of undefined

      35 | 
      36 | beforeAll(async () => {
    > 37 |   await preloadAll();
         |         ^
      38 | });
      39 | 
      40 | describe('SSR - Custom Page', () => {

      at node_modules/jest-next-dynamic/index.js:40:38
      at node_modules/jest-next-dynamic/index.js:12:52
          at Array.map (<anonymous>)
      at preloadAll (node_modules/jest-next-dynamic/index.js:12:37)

As far as I have researched, whats going on is that in a jest node environment is that we are trying to preload a SSR false dynamic component, which will be undefined as it should only be render in a client. So in conclusion LoadableComponent at line 35 at the file https://github.com/FormidableLabs/jest-next-dynamic/blob/master/index.js is undefined.

LoadableComponent.preload
          ? LoadableComponent.preload()
          : LoadableComponent.render.preload();

Is there a way around to fix this? If we set the jest env too jsdom works but we NEED to set a node jest env to simulate a Server Side Rendering test, so that solution does not work for us.

I have tried locally the following change for lines 35, 36 and 37 at file https://github.com/FormidableLabs/jest-next-dynamic/blob/master/index.js that worked:

if(LoadableComponent.preload) {
          LoadableComponent.preload();
        } else if(LoadableComponent.render)  {
          LoadableComponent.render.preload();
        }

Is this a possible fix for the library?

Broken as of Next 8.0.4

Upgrading from 8.0.3 ->8.0.4 it appears this has broken unfortunately.

I now get the error:

Cannot find module 'function () {
            return (0, _interopRequireWildcard2.default)(require('./Search/Search'));
          }' from 'Header.js'

image

Jest is not defined

Error msg:

ReferenceError: jest is not defined
    at Object.<anonymous> (C:\Users\alilo\Documents\NextjsWithTS\nextjs-boilerplate\node_modules\jest-next-dynamic\index.js:53:3)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.H76Q (C:\Users\alilo\Documents\NextjsWithTS\nextjs-boilerplate\.next\server\pages\__tests__\index.test.js:121:18)
    at __webpack_require__ (C:\Users\alilo\Documents\NextjsWithTS\nextjs-boilerplate\.next\server\pages\__tests__\index.test.js:23:31)    
    at Module.hF5B (C:\Users\alilo\Documents\NextjsWithTS\nextjs-boilerplate\.next\server\pages\__tests__\index.test.js:190:75) {
  type: 'ReferenceError'
}

index.test.js

import HomePage from '@/pages/index';
import preloadAll from 'jest-next-dynamic';
import { render } from 'src/testUtils/testUtils';

beforeAll(async () => {
  await preloadAll();
});
describe('Home page', () => {
  it('Should... WHEN...', () => {
    render(<HomePage />);
  });
});

jest config

module.exports = {
  roots: ['<rootDir>/src'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'jsx'],
  testPathIgnorePatterns: ['<rootDir>[/\\\\](node_modules|.next)[/\\\\]'],
  transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(ts|tsx)$'],
  transform: {
    '^.+\\.(ts|tsx|js|jsx)$': 'babel-jest',
  },
  watchPlugins: [
    'jest-watch-typeahead/filename',
    'jest-watch-typeahead/testname',
  ],
  moduleNameMapper: {
    '\\.(css|less|sass|scss)$': 'identity-obj-proxy',
    '\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js',
    'src/(.*)': '<rootDir>/src/$1',
    '@/pages/(.*)': '<rootDir>/src/pages/$1',
    '@/components/(.*)': '<rootDir>/src/components/$1',
  },
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
};

.babelrc

{
  "presets": ["next/babel"],
  "plugins": ["babel-plugin-dynamic-import-node"]
}
"devDependencies": {
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.8.3",
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.35",
    "@types/react": "^17.0.3",
    "@typescript-eslint/eslint-plugin": "^4.18.0",
    "@typescript-eslint/parser": "^4.18.0",
    "babel-jest": "^26.6.3",
    "babel-plugin-dynamic-import-node": "^2.3.3",
    "eslint": "^7.22.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-react": "^7.22.0",
    "jest": "^26.6.3",
    "jest-next-dynamic": "^1.0.1",
    "jest-watch-typeahead": "^0.6.1",
    "typescript": "^4.2.3"
  }

What could be the reason for it? how might my code affect an external module?

Does this work with next8?

I've been trying to find a way to test dynamic import components but nothing is working. Just wanted to know if this still works with next 8

jest-next-dynamic: ensure actions use node18

This project is referencing old versions of Node we no longer want to support (I.e < 18). In order to conform with Nearform_Commerce OSS standards, please convert the action from in matrices and instead run for node 18.

Cannot read property 'preload' of undefined

With nextjs v13.1.7-canary.3, the 'preload' function no longer exists on next/dynamic components with {ssr: false}, causing an error Cannot read property 'preload' of undefined

Not compatible with Jest's resetMocks option

Hello,

First thank you for this great lib 😄

It seems that the way to use this library described in the documentation is not compatible with the resetMocks option of Jest.

Indeed, next/dynamic is only mocked for the first test and the real one is restored from the second test.

I don't know if it could be managed by the lib directly but it could be at least documented.

Regards,
Josselin BUILS

TypeError: require.resolveWeak is not a function

I am getting the following error when attempting to dynamically load within a babel compiled component:

TypeError: require.resolveWeak is not a function

The compiled contents looks like so:

var AuthMenu = (0, _dynamic.default)(function () {
  return _promise.default.resolve().then(function () {
    return (0, _interopRequireWildcard2.default)(require("@connect/web-auth/lib/container/AuthMenu/AuthMenu"));
  });
}, {
  loadableGenerated: {
    webpack: function webpack() {
      return [require.resolveWeak("@connect/web-auth/lib/container/AuthMenu/AuthMenu")];
    },
    modules: ["@connect/web-auth/lib/container/AuthMenu/AuthMenu"]
  }
});

I am wondering if this package supports this scenario?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.