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



我有一个函数,它返回另一个函数:

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]

但我不知道如何把它们搭配起来。

函数是通过引用进行比较的,因此,如果在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);

注意,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

但我不清楚这个目标。。。

最新更新