erikos93
erikos93

Reputation: 687

Mock lodash _orderBy method with Jest

I'm wondering how I can mock a lodash _orderBy method with Jest and make sure that it has been called with the arguments as below.

My Vue.component method sliceArray

 sliceArray: function(array) {
          let val = _.orderBy(array, "orderDate", "desc");
          return val.slice(0, this.numberOfErrandsLoaded);
        }

This is what I have so far:

import _ from "lodash";
jest.unmock("lodash");

it("Check orderBy method from lodash", () => {
    _.orderBy = jest.fn();
    expect(_.orderBy).toHaveBeenCalledWith([], "orderDate", "desc");
  });

The current error message:

Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: [], "orderDate", "desc"

Number of calls: 0

Thanks beforehand!

/ E

Upvotes: 1

Views: 9429

Answers (2)

Chocho
Chocho

Reputation: 81

Fixed Melchia's solution:

import lodash from "lodash";
const spyOrderByLodash = jest.spyOn(_, 'orderBy');

beforeEach(() => {
    jest.clearAllMocks();
  });

it("Check orderBy method from lodash", () => {
    expect(spyOrderByLodash).toHaveBeenCalledWith([], "orderDate", "desc");
  });

Upvotes: 0

Melchia
Melchia

Reputation: 24284

This what I do test imported libraries. I use jest.spyOn(object, methodName)

import * as _ from "lodash";
const spyOrderByLodash = jest.spyOn(_, 'orderBy');

it("Check orderBy method from lodash", () => {
    expect(spyOrderByLodash).toHaveBeenCalledWith([], "orderDate", "desc");
  });

Don't forget to clearAllMocks before each test (optional but a must if you have multiple tests in a single file):

  beforeEach(() => {
    jest.clearAllMocks();
  });

Upvotes: 1

Related Questions