如果我在構造函數中使用 Proxy:get,為什麼 mocha chai 不應該證明`return this`的身份?

布萊克尼克斯

我想寫一個類,處理未定義的屬性。我還想返回this能夠鏈接方法來創建域特定語言 (DSL)。

我從構造函數返回一個代理,以處理未定義的屬性。現在在測試實例時,它確實發生了,這return this並不能證明與實例相同。我擔心由此產生的錯誤,儘管我可以按預期鏈接方法。

這是一個顯示行為摩卡 測試。替換o.that().should.not.equal(o);o.that().should.equal(o);一條指令中的with以查看它是如何失敗的。

require('chai').should();

describe('chai testing classes using Proxy', () => {
    it('asserts object identity, if an instance method returns this', () => {
        const o = new class NormalClass{ }
        o.that = function() { return this; }
        o.that().should.equal(o);
    });
    it('observes the same behaviour for constructors returning a dummy Proxy', () => {
        const o = new class ProxyClass{
            constructor() { return new Proxy(this, {}); }
        }
        o.that = function() { return this; }
        o.that().should.equal(o);
    });
    it('requires deep.equal on the other hand, if the Proxy handles get', () => {
        const o = new class ProxyClassPlusGet{
            constructor() {
                return new Proxy(this, {
                    get: function(target, prop) { return target[prop]; },
                });
            }
        }
        o.that = function() { return this; }
        o.that().should.deep.equal(o);
        o.that().should.not.equal(o);
    });
});
貝爾吉

您的實現在o.that() === o產量範圍內有效true

但它不適用於 getter,這會干擾 chai 的should. 你可以用

const o = new Proxy({
    get self() { return this; },
    that() { return this; },
}, {
    get(target, prop) { return target[prop]; },
});
console.log(o.self === o);
console.log(o.that() === o);

這是為什麼?因為你的get陷阱被打破了,忽略了屬性訪問接收者這將舉行代理o,但是當你這樣做return target[prop],然後target將接收器。您可以使用Reflect.get以下方法修復它

const o = new Proxy({
    get self() { return this; },
    that() { return this; },
}, {
    get(target, prop, receiver) {
        return Reflect.get(target, prop, receiver);
//                                       ^^^^^^^^
    },
});
console.log(o.self === o);
console.log(o.that() === o);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我的Mocha / chai错误抛出测试失败?

使用Mocha和Chai ReactJS进行调试

使用Mocha和Chai,AssertionError测试GET端点

使用Mocha和Chai声明Javascript数组中包含的值

Mocha Chai Sequelize:我无法使测试失败

如何使用Mocha Chai测试Vue方法

使用Mocha Chai测试node.js中引发的错误

Mocha 和 Chai GET 请求测试不起作用

使用 Mocha 和 Chai 测试 React

如何使用 webdriverIO、Mocha 和 Chai 验证元素已消失

如何使用 mocha、chai 和量角器等待元素

如何使用 mocha/chai 设置 jwt cookie?

為什麼我們應該在聲明函數的同一個文件中包含函數原型的頭文件?

Mocha + Chai + NodeJS 永遠不會失敗,但它應該

重構 golang 函數——應該使用什麼類型?

為什麼我不能在函數中設置我的構造函數?

為什麼我的 onsubmit 驗證函數沒有提交我的函數?

我應該在顫振中使用 bloc 進行 firebase 身份驗證嗎?

什麼時候應該使用接口/抽像類,什麼時候不應該?

為什麼不調用移動構造函數?

為什麼我的 IFS 函數不適用於 QUERY?

為什麼我的函數不返回新字符串?

為什麼 x 不會留下來,我應該如何讓它留在板上

為什麼我的 iOS 應用無法使用 Node.js Agora 令牌服務器創建的令牌通過 AgoraRtcEngineKit 進行身份驗證?

C++ 結構和函數聲明。為什麼不編譯?

為什麼#undef 不適用於我的函數?

為什麼我應該更喜歡單獨的函數而不是 C++ 中的函數式編程的靜態方法?

為什麼即使用戶已通過身份驗證,它也會將我引導回登錄頁面?

為什麼我們需要在我們的應用程序中使用 OKTA 進行身份驗證或身份驗證?