Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting `TypeError: jest.fn is not a function`

I'm trying to create the following unit test using Jest.

jest.dontMock("pointsAwardingActions.js");
describe("points awarding actions", () => {
  describe("award points", () => {
    it("should dispatch begin ajax action", () => {
      var pointsAwardingActions = require("pointsAwardingActions.js");
      const mockedDispatch = jest.fn();
    });
  });
});

But I'm getting the following error after running npm test.

TypeError: jest.fn is not a function

This is some section of my package.json:

{
  "scripts": {
    "test": "jest"
  },
  "author": "alayor",
  "license": "ISC",
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testFileExtensions": ["spec.js"],
    "moduleFileExtensions": ["js"],
    "collectCoverage": "true"
  },
  "dependencies": {
    "babel-cli": "6.8.0",
    "babel-core": "6.8.0",
    "babel-jest": "^6.0.1",
    "babel-loader": "6.2.4",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-polyfill": "6.8.0",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.5.0",
    "babel-preset-react-hmre": "1.1.1",
    "expect": "1.19.0",
    "express": "4.13.4",
    "jest": "^0.1.40",
    "jest-cli": "^0.8.1",
    ...
  }
}

What could be the reason I'm getting that error?

like image 691
alayor Avatar asked Sep 07 '17 02:09

alayor


People also ask

What does Jest fn () mean?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest.

How do you mock a promise in Jest?

In order to mock asynchronous code in Jest, more specifically Promises, you can use the mockResolvedValue function. This will mock the return value of the Promise to be 42. In order to test a Promise in Jest, you need to turn your it block into async in order to use the await keyword in front of an expect statement.

How do you mock a file in Jest?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.


2 Answers

The jest object is automatically in scope within every test file, so there's no need to import it explicitly. If you do want to import the jest object directly, you want to import the jest-mock module, not the jest-cli module, via:

// Not necessary inside a Jest test file
import jest from 'jest-mock';

const mock = jest.fn();
like image 55
Rick Hanlon II Avatar answered Sep 19 '22 08:09

Rick Hanlon II


It is a bit weird that documentation isn't mentioning that jest is not require('jest'); but require('jest-mock'), the following code should work on v22:

const jest = require('jest-mock');
const spy = jest.fn();
like image 20
Anatoliy Avatar answered Sep 22 '22 08:09

Anatoliy