2

Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.

The error I am getting is

Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js

Steps to Reproduce

With the following three files

  • src/index.js
export const sum = (a, b) => a + b;
  • test/index.spec.js
import { sum } from '../src/index';

const expect = require('chai').expect;

describe('Testing Index', () => {
    it('Testing sum', () => {
        expect(sum(7, 13)).to.equal(20);
    });
});
  • package.json
{
  "name": "mocha-debug",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "mocha \"./test/**/*.spec.js\""
  },
  "license": "ISC",
  "devDependencies": {
    "chai": "4.3.4",
    "mocha": "9.1.4"
  }
}

and using node v14.18.2, run yarn install and

yarn test

> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`

Notes

I've found a related issue that recommends using babel with --require @babel/register, but wasn't able to get over the error.

I've set up a test repo to make it easy to reproduce the issue

https://github.com/simlu/mocha-debug

Question

What am I doing wrong here? How do I get the tests to run successfully?

vincent
  • 1,953
  • 3
  • 18
  • 24
  • 1
    Probably you need to add a file extension when importing the modules, e.g. `import { sum } from '../src/index.js'`. – GOTO 0 Jan 21 '22 at 23:02
  • @GOTO0 hum... I think I was staring at this way too long. I could swear I've tried this before... Thank you! – vincent Jan 21 '22 at 23:12
  • 1
    You're welcome! :D Note that you could also use [subpath patterns](https://nodejs.org/docs/latest-v14.x/api/packages.html#packages_subpath_patterns) in your package.json to import files without having to add ".js" to the name (this works in Node 14 and later). – GOTO 0 Jan 21 '22 at 23:48

1 Answers1

0

I solved it by just adding the file extension in my case I was importing my mongodb model so I imported with the file extension .ts

var Employee = require('../models/Employee.ts')

Which solved the issue