测试从另一个函数返回的函数类型

问题描述 投票:0回答:2

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

    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]

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

javascript node.js typescript testing jestjs
2个回答
2
投票

函数是通过引用进行比较的,因此,如果您在

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);

1
投票

注意

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

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

属于类型

returnedFunction

您需要知道调用了哪个函数吗?除非您保留对函数的引用(例如在对象中),或者为它们分配唯一标识符,否则您不能真正使用

toString()
等于函数、事件,这只能保证两个函数的字符串表示形式(代码)是一样的。

我会尝试:

let returnedFunction = () => {};
returnedFunction.id = "returnedFunction";

const returnFunction = () => {
    const fn = returnedFunction;
    // Do stuff
    return fn;
}

// getting id of the returned function
returnFunction().id

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

© www.soinside.com 2019 - 2024. All rights reserved.