【问题标题】:How to use Jest to test higher order function for Redux action with nested function如何使用 Jest 测试具有嵌套函数的 Redux 操作的高阶函数
【发布时间】:2020-04-02 03:07:24
【问题描述】:

我正在使用 Jest 测试 Redux 操作函数 fn1。 fn1 是包装 fn2 的高阶函数。我的测试只是为了确保在执行 fn1 时调用 fn2。似乎不起作用。我正在考虑使用jest.spyOn,但这似乎没有意义。

myActions.js:

export const fn1 = obj => {
  return strInput => {
    fn2(strInput, obj);
  };
};

export const fn2 = (strInput, obj) => ({name:strInput, obj});

myAction.test.js:

import {fn1, fn2} from myAction.test.js

it("should call fn2", () => {
    fn1({test:"test"})("David")
    expect(fn2).toHaveBeenCalled();
  });

【问题讨论】:

    标签: reactjs testing redux jestjs higher-order-functions


    【解决方案1】:

    在某种程度上,我觉得您正在尝试做的是测试实现细节而不是函数的 API,但在单元测试中,您确实希望根据指定输入,即f(x) = y,测试输入x产生输出y

    大概您的fn2 将有自己的单元测试,因此您可以假设它在用于其他功能(如fn1)时经过测试并正确。

    这是我将如何测试fn1

    it("should compute composed value", () => {
      expect(fn1({ test: "test" })("David")).toEqual({
        name: "David",
        obj: { test: "test" }
      });
    });
    

    我想说监视或断言函数调用的典型用例是回调的情况。回调不是函数实现的一部分,但通常是外部副作用。

    const fn3 = (value, callback) => {
      // bunch of code logic
      callback(value);
      // more code logic
      return true;
    };
    
    it("should callback function", () => {
      const cb = jest.fn();
      fn3(3, cb);
      expect(cb).toHaveBeenCalledWith(3);
    });
    

    不是真正的答案的一部分,但信息丰富

    此时我想指出一个命名错误:高阶函数 vs 柯里化

    Higher Order Function 是一个将函数作为输入并返回一个新函数的函数。示例包括.map.filter、功能组合

    const plus3 = x => x + 3; // a first order function
    const double = (fn, v) => fn(v) * 2; // a higher order function
    
    const plus3AndDouble = x => double(plus3, x); // a (decorated) first order function
    
    console.log(plus3AndDouble(0)); // (0 + 3) * 2 = 6
    console.log(plus3AndDouble(1)); // (1 + 3) * 2 = 8

    您所完成的实际上是一个名为currying 的概念,其中您采用一个接受多个输入的函数并将其转换为一系列函数,每个函数接受一个输入。

    const foo = (a, b, c) => a + b * c;
    const bar = a => b => c => foo(a, b, c);
    
    console.log(foo(1, 2, 3) === bar(1)(2)(3)); // true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      相关资源
      最近更新 更多