簡體   English   中英

測試從另一個函數返回的函數類型

[英]Testing the function type returned from another function

我有一個返回另一個函數的函數:

    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

但我不清楚那個目標......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM