【问题标题】:Is there an easy way of altering confirm and alerts in this sinon.spy mocha example在这个 sinon.spy mocha 示例中是否有一种简单的方法来更改确认和警报
【发布时间】:2016-10-24 18:55:36
【问题描述】:

我稍作改动以隐藏我无法分享的细节,但我正在测试的示例函数(我们称之为 checkbro.js)在这里...

checkbro.js

function saveRecord(context) {
        if (!checkIfBro.knowsABro(context.currentRecord)) {
            if (confirm('Do you Bro?')) {
                context.currentRecord.setValue('bro', -10, true);
            } else {
                alert('Please someone has to be a bro');
            }
        }
        return true;
    }

我的一个测试示例(它失败了 ReferenceError: confirm is not defined)...

checkbro.spec.js

it('should only execute for create new bro master', function() {
        let checkIfBro = { knowsABro: sinon.spy() };
        let confirm = {confirm: sinon.spy()};
        let record = {currentRecord: { setValue: sinon.spy()}};
        let checkIfBroRec = requirejs('contacts/checkbro', [checkIfBro, log]);
        checkIfBroRec.saveRecord({ record: record });
        checkIfBroRec.knowsABro.called.should.be.true;
        record.currentRecord.setValue.called.should.be.true;
    });

一点上下文,我已经完成了很多浏览器测试并且刚刚进入单元测试,所以这里有一些学习曲线。任何更好地使用 sinon 或其他模块我都在听。这也是开发者写的,现在我接手了。

【问题讨论】:

  • 你在哪里将confirm spy传递给函数?如果你使用requirejs('contacts/checkbro', [checkIfBro, log]);这一行传递依赖项,那么你应该包含confirm spy,所以函数会有一个引用。跨度>

标签: javascript unit-testing requirejs mocha.js sinon


【解决方案1】:

失败了ReferenceError: confirm is not defined

在上面的代码中if (confirm('Do you Bro?')) 使用let confirm = {confirm: sinon.spy()} 作为函数。这应该抛出TypeError: confirm is not a function:

var confirm = {};
function foo () {
    if(confirm()){}
}

foo(); // TypeError: confirm is not a function

因此可以肯定的结论是不是checkIfBroRec.saveRecord({ record: record })导致代码到达if (confirm('Do you Bro?')),因此问题必须出在:

let checkIfBroRec = requirejs('contacts/checkbro', [checkIfBro, log]);

很遗憾,这部分代码没有完全显示在上面的代码片段中,因此我无法评估导致问题的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2012-07-02
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多