用Jest模拟lodash _orderBy方法

时间:2020-03-10 15:26:28

标签: javascript unit-testing vue.js jestjs

我想知道如何使用Jest模拟lodash _orderBy方法,并确保已使用以下参数调用了该方法。

我的Vue.component方法sliceArray

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

这是我到目前为止所拥有的:

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

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

当前错误消息:

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

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

Number of calls: 0

预先感谢!

/ E

1 个答案:

答案 0 :(得分:0)

这就是我测试导入的库的方法。我使用jest.spyOn(object, methodName)

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

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

不要忘记在每次测试之前清除allMocks(可选,但如果单个文件中有多个测试,则必须这样做):

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