Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock curry function with Jest?

Tags:

jestjs

add.js

export default a => b => a+b;

module.js

import add from './add';

export default {
    add1: n => add(1)(n),
};

test/module.js

import add from '../add';
import module from '../module';

jest.mock('../add', () => () => jest.fn());

module.add1(6);
expect(add.mock.calls).toHaveLength(1);

this can be called, but add wouldn't be a mock function, instead add() is a mock function, but the call params were not recorded correctly.

jest.mock('../add', () => () => jest.fn(a => b => a+b));

has also tried this, which doesn't seem to work correctly as well.

jest.mock('../add', jest.fn(a => b => a+b));

this would throw the inline function error

Is there a correct way to mock curry function at the moment?

like image 504
zhenyulin Avatar asked Feb 21 '18 12:02

zhenyulin


2 Answers

Simple version should look like this

jest.mock('../add', () => (a) => jest.fn(b => a+b));

So you mock add module with a function that return that when gets called it returns the spy, problem you can't test anything on the spy.

So we need to refactor it so you have the add1 think as a spy in scope of the test

import add from '../add'
jest.mock('../add', () => jest.fn)

const addC = jest.fn()
add.mockImplemetation((a) => {
  addC.mockImplementation((b => a+b)
  return addC
})
like image 96
Andreas Köberle Avatar answered Oct 17 '22 03:10

Andreas Köberle


I know this is a bit old but with the following answer I would have saved so much time...

import module from "./module";

const mockOperation = {
  add: jest.fn()
};

jest.mock("./add", () => () => {
  return mockOperation.add;
});

describe("add ", () => {
  it("is called at least once", () => {
    module.add1(6);
    expect(mockOperation.add.mock.calls).toHaveLength(1);
  });
});

A very importante thing: the constant function that you want to mock must start with the word mock. Otherwise it will throw an error.

const mockOperation = {
  add: jest.fn()
};

With the mockOperation constant assigned to the add file, by reference is calling to it's add method which is a jest.fn()

like image 32
Nahuelgrc Avatar answered Oct 17 '22 04:10

Nahuelgrc