'Jest not found while running JEST in docker container

I have created below simple Dockerfile:

FROM node:16.7.0
WORKDIR /app
COPY . .
RUN npm install
# ENTRYPOINT [ "npm" ]
CMD ["sh", "-c", "tail -f /dev/null"]

I have added a cmd line with "tail -f /dev/null" to check exactly what's the issue if I issue npm test inside the container.

As soon as I run npm test inside the container --> It throws me below error

# npm test

> [email protected] test
> jest --verbose

sh: 1: jest: not found

my package.json

{
  "name": "docker-jest",
  "version": "1.0.0",
  "description": "Package for Jest",
  "scripts": {
    "test": "jest --verbose"
  },
  "Dependencies": {
    "@babel/node": "*",
    "@babel/core": "*",
    "@babel/preset-env": "*",
    "babel-jest": "*",
    "jest": "*"
  },
  "license": "ISC"
}

sum.js

function sum(a, b) {
  return a + b;
}

module.exports = sum;

sum.test.js

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Even if I disable CMD and enable ENTRYPOINT and after the build, if I issue:

docker run -it <imagename> test 

It throws me the same error, I see the npm install is installing but can't find the jest @ /usr/local/lib/node_modules/ as I see the node modules are deployed in location/usr/local/lib/node_modules/ inside the container, and if I issue jest it says jest not found. If I, run the same without the container it works fine. I mean just in the command line after running npm install and then npm run test.

Can anyone assist me with why I'm getting this error and how to fix it?

-----------UPDATE------------- Found the fix, it was because of my corrupted package-lock file. When I tested in local without the docker, I somehow corrupted the lock file, and later stage when I build and try to run using docker, the corrupted lock file was causing a whole lot of issues. So I deleted it and again ran thru docker...It's working as expected.



Solution 1:[1]

I had the same issue and the fix for me was running npm install -g jest (or yarn global add jest).

To add this to your package.json do the following:

"scripts: {
  "test": "npm install -g jest && jest --verbose"
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JHamm