简体   繁体   English

Sinon.JS - 如何从存根中获取参数?

[英]Sinon.JS - How can I get arguments from a stub?

I am trying to use Sinon to test a JS component which looks a bit like this... 我正在尝试使用Sinon来测试看起来有点像这样的JS组件......

import Bootbox from "../helpers/bootbox";
import Guard from "../helpers/guard";
import UrlHelper from "../helpers/url-helper";

export default class DeleteButton {

    /**
     * Creates an instance of DeleteButton.
     * 
     * @param {object} element The DOM element to make into a delete button.
     * 
     * @memberOf DeleteButton
     */
    constructor(element) {
        Guard.throwIf(element, "element");

        this.deleteUri = element.getAttribute("data-delete-uri") || UrlHelper.current.url().split('?')[0];        
        this.title = element.getAttribute("data-title") || `Delete the item?`;
        this.cancelText = element.getAttribute("data-cancel") || `Cancel`;
        this.confirmText = element.getAttribute("data-confirm") || `Remove`;
        this.message = element.getAttribute("data-message") || `Do you want to delete the item? This cannot be undone.`;
        this.successUri = element.getAttribute("data-success-uri");
        this.errorMessage = element.getAttribute("data-error-message") || `Unable to complete operation.`;
    }

    /**
     * Shows failure of deletion.
     * 
     * @memberOf DeleteButton
     */
    showFailed() {
        Bootbox.alert({
            message: this.errorMessage,
            size: `small`,
            backdrop: true
        });
    }
}

The test looks like this... 测试看起来像这样......

it("Can show a fail message", function() {
    $("body").append(`<a class="js-delete-button" data-id="123" data-delete-uri="/delete/123">Delete</a>`);
    let objUt = new DeleteButton($(".js-delete-button").get()[0]);
    let bootboxAlertStub = Sinon.stub(Bootbox, 'alert');
    objUt.showFailed();
    let args = bootboxAlertStub.args;
    expect(args.message).to.equal(objUt.errorMessage);
});

But I can't get past the line let bootboxAlertStub = Sinon.stub(Bootbox, 'alert'); 但我无法通过该行let bootboxAlertStub = Sinon.stub(Bootbox, 'alert'); because I get an error from Karma saying 'Should wrap property of object'. 因为我从Karma那里得到一个错误,说'应该包装对象的属性'。 I've tried wrapping it up in a Sinon.test wrapper as well and using this.stub but the error the is even more obtuse. 我已经尝试将它包装在Sinon.test包装中并使用this.stub,但错误更加迟钝。

I've been through the Sinon.JS docs and searched online but I'm stuck. 我已经通过Sinon.JS文档并在线搜索但我被卡住了。 The code works fine. 代码工作正常。

I have looked at this posting, which is similar - Stubbing a class method with Sinon.js but it's not quite the same. 我看过这个帖子,它是类似的 - 用Sinon.js创建一个类方法,但它并不完全相同。

Looking at the actual underlying bootbox JavaScript file I'm effectively trying to stub a method that looks a bit like this (cut down)... 看看实际的底层bootbox JavaScript文件,我实际上是在试图找到一个看起来有点像这样的方法(减少)......

  exports.alert = function() {
    // do something
  };

The JS file then returns the exports at the end... 然后JS文件最后返回导出...

  return exports;

Looking at some Github postings it seems that it may not be possible to stub these particular calls as the underlying calls are utility functions rather than object functions. 看一些Github帖子似乎可能无法存根这些特定的调用,因为底层调用是实用函数而不是对象函数。

I have mitigated this (in a horrible way) by changing my Bootbox wrapper class as follows... 我通过更改我的Bootbox包装类来缓解这种情况(以一种可怕的方式),如下所示......

export default {

    /**
     * Generates an alert box.
     * 
     * @param {any} options
     */
    alert: function(options) {
        window.bootbox.alert(options);
    },

    /**
     * Generates a confirmation dialog.
     * 
     * @param {any} options
     */
    confirm: function(options) {
        window.bootbox.confirm(options);
    }
}

This solves one problem and introduces another. 这解决了一个问题并引入了另一个问题。 While I can now stub Bootbox, when stubbed I can't get the arguments.... 虽然我现在可以存根Bootbox,但当存在时我无法获得参数....

(from the test) (来自测试)

let args = bootboxAlertStub.args;

This is frustrating - The arguments are passed as a complex argument so a 'calledWith' assertion isn't going to cut it. 这令人沮丧 - 参数作为一个复杂的参数传递,因此'calledWith'断言不会削减它。

Is there any way I can get the arguments for a stub? 有什么方法可以得到存根的参数吗?

Thanks to Matt Mokary (if you want to submit an answer I'll give you the credit for this one) 感谢Matt Mokary (如果你想提交一个答案,我会给你这个奖励

I edited my test as follows... 我按如下方式编辑了我的测试...

it("Can show a fail message", Sinon.test(function() {        
    $("body").append(`<a class="js-delete-button" data-id="123" data-delete-uri="/delete/123">Delete</a>`);
    let objUt = new DeleteButton($(".js-delete-button").get()[0]);
    let bootboxAlertStub = this.stub(Bootbox, 'alert');
    objUt.showFailed();
    Sinon.assert.called(bootboxAlertStub);
    let options = bootboxAlertStub.getCall(0).args[0];
    expect(options.message).to.equal(objUt.errorMessage);
}));

The thing that fixed it was, as Matt suggested, using... 正如马特建议的那样,解决它的问题是......

bootboxAlertStub.getCall(0);

with the slight adjustment of 稍作调整

bootboxAlertStub.getCall(0).args[0];

to get the first argument (which is the options object). 获取第一个参数(这是选项对象)。

As an aside, discovering that I can use console.log to see what's going on when I'm running a test through Phantom and Karma was both a revelation and a headslapping moment. 顺便说一句,发现我可以使用console.log查看当我通过Phantom和Karma进行测试时发生的事情既是一个启示,也是一个令人头疼的时刻。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM