【问题标题】:Testing the function type returned from another function测试从另一个函数返回的函数类型
【发布时间】:2020-10-07 18:39:36
【问题描述】:

我有一个返回另一个函数的函数:

    const returnedFunction = () => {}

    const returnFunction = () => {
        const function = returnedFunction();

        // Do stuff

        return function;
    }

我想测试从returnFunction 返回的函数类型是returnedFunction。 Jest 似乎在回复中明白了这一点:

    expect(received).toBe(expected) // Object.is equality

    Expected: "[Function returnedFunction]"
    Received: [Function returnedFunction]

但我不知道如何匹配它们。

【问题讨论】:

  • 返回的函数是否有机会在其自己的模块中导出?如果是这样,您可以模拟它并期望它被调用?
  • @Rezaa91 但我希望看到正确的类型被返回,我已经在用间谍来做这件事了。我用一个更好的例子更新了这个问题,因为我不只是执行函数并返回我在它之间做的事情。
  • 在您的示例中,returnFunction() 实际上并没有返回一个函数,它调用了returnedFunction(),它返回一个空对象,然后执行 // 一些操作,然后返回该对象。
  • @Wodlo 啊,这是一个好点...错过了,因为在我的实际代码中,该函数然后返回另一个函数:)
  • typechecker 在 typescript 中的工作是检查程序中的类型是否与您编写的类型匹配。为什么要编写测试来验证类型?

标签: javascript node.js typescript testing jestjs


【解决方案1】:

函数通过引用进行比较,因此如果您在 returnedFunction 和测试中构造函数,即使它们看起来相同,它们也不会被视为相等。

您应该介绍一些在测试和代码之间共享引用的方法。例如,

// Note that sharedFn can now be used in your test for comparison
const sharedFn = () => {};
const returnedFunction = () => { return sharedFn; };

...

const received = returnFunction();
expec(received).toBe(sharedFn);

【讨论】:

    【解决方案2】:

    注意function是javascript中的保留关键字,变量不能命名为function

    我不确定你到底是什么意思

    类型为returnedFunction

    您需要知道调用了哪个函数吗?除非您保留对函数的引用(例如在对象中),或者为它们分配唯一标识符,否则您不能真正等同于函数,事件与toString(),这只会保证两个函数的字符串表示(代码)是一样的。

    我会尝试:

    let returnedFunction = () => {};
    returnedFunction.id = "returnedFunction";
    
    const returnFunction = () => {
        const function = returnedFunction;
        // Do stuff
        return function;
    }
    
    // getting id of the returned function
    returnFunction().id
    

    但我不清楚这样做的目标......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2022-12-01
      • 1970-01-01
      相关资源
      最近更新 更多