【问题标题】:Mock lodash _orderBy method with Jest用 Jest 模拟 lodash _orderBy 方法
【发布时间】:2020-03-10 15:26:28
【问题描述】:

我想知道如何使用 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

【问题讨论】:

  • 尝试模拟 lodash/orderBy.js 而不是 _.orderBy = jest.fn()。在你直接重写的时候,你的组件已经导入了lodash并以原版执行。
  • 顺便说一句,您真的需要验证吗?如果你只是验证渲染结果呢?

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

这就是我测试导入库的工作。我用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();
  });

【讨论】:

  • 有趣。恐怕我仍然收到与以前相同的错误消息!
  • 可能是因为spyOn中的额外空间:orderBy
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2019-11-22
  • 2019-08-04
  • 2020-08-08
  • 2021-08-04
相关资源
最近更新 更多