Skip to content

Cannot require a module when using typescript #846

@jasonwilliams

Description

@jasonwilliams

Describe the bug

Im trying to migrate next-page-tester from jest to vitest. When running the test runner I get the error:

Error: [next-page-tester] Failed to load "DefaultApp" file due to Error: Cannot find module 'workspace/next-page-tester/src/_app/DefaultApp'
Require stack:
- /workspace/next-page-tester/src/loadFile.ts
 ❯ Object.loadFile src/loadFile.ts:18:11
     16| }): FileType {
     17|   try {
     18|     return require(absolutePath);
       |           ^
     19|   } catch (e: unknown) {
     20|     const baseName = path.basename(absolutePath);
 ❯ getDefaultAppFile src/_app/getAppFile.ts:27:9
 ❯ Object.getAppFile src/_app/getAppFile.ts:23:9
 ❯ loadPageFiles src/getNextFiles.ts:27:13
 ❯ Object.loadErrorPageFiles src/getNextFiles.ts:65:12
 ❯ Object.makeNotFoundPageObject src/404/makeNotFoundPageObject.ts:26:11

However running the same test in Jest passes fine.

The above looks like it needs the file extension to the module, so when i manually add that I get a different error.

Error: [next-page-tester] Failed to load "DefaultApp.tsx" file due to SyntaxError: Cannot use import statement outside a module
 ❯ Object.compileFunction node:vm:352:18
 ❯ Object.loadFile src/loadFile.ts:18:11
     16| }): FileType {
     17|   try {
     18|     return require(absolutePath);
       |           ^
     19|   } catch (e: unknown) {
     20|     const baseName = path.basename(absolutePath);
 ❯ getDefaultAppFile src/_app/getAppFile.ts:27:9

Module workspace/next-page-tester/src/_app/DefaultApp.tsx:1 seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package "" 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: {
    deps: {
      inline: [
        ""
      ]
    }
  }
}

Reproduction

System Info

System:
    OS: macOS 11.6.1
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 596.19 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 17.6.0 - ~/.nvm/versions/node/v17.6.0/bin/node
    npm: 8.5.1 - ~/.nvm/versions/node/v17.6.0/bin/npm
  Browsers:
    Chrome: 98.0.4758.102
    Safari: 14.1.2
  npmPackages:
    vitest: 0.5.5 => 0.5.5

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions