【问题标题】:How to stub constructor如何存根构造函数
【发布时间】:2019-09-21 17:32:17
【问题描述】:

我正在编写 uni-test 并尽可能地隔离我的代码。我正在使用 Mocha 和 chai 编写测试和 ES5 语法。 问题是,我找不到任何存根构造函数的解决方案。

Q.reject(new Error(obj.someFunction());

在上面的例子中,我知道如何测试promise,如何存根我的内部函数,但是我如何存根Error 构造函数?以及如何查看callWithExactly()等。

oStubSomeFunction = sinon.stub(obj, "someFunction")

我正在使用正常功能。我在ChaiDocumentation没有找到任何相关的例子

【问题讨论】:

    标签: javascript mocha.js chai assertion


    【解决方案1】:

    如果您真的想要存根Error 构造函数,您可以使用the Node.js global namespace

    code.js

    exports.func = function() {
      return new Error('error message');
    }
    

    code.test.js

    const { func } = require('./code');
    const sinon = require('sinon');
    const assert = require('assert');
    
    describe('func', function () {
      it('should create an Error', function () {
        const errorStub = sinon.stub(global, 'Error');  // <= stub the global Error
        errorStub.callsFake(function(message) {  // <= use callsFake to create a mock constructor
          this.myMessage = 'stubbed: ' + message;
        });
    
        const result = func();
    
        errorStub.restore();  // <= restore Error before doing anything else
    
        assert(result.myMessage === 'stubbed: error message');  // Success!
        sinon.assert.calledWithExactly(errorStub, 'error message');  // Success!
      });
    });
    

    如果您这样做,您将需要在执行任何其他操作之前恢复 Error...即使断言也可以使用 Error,因此原始的 Error 需要到位,以防断言失败。


    只监视Error 会更安全:

    const { func } = require('./code');
    const sinon = require('sinon');
    
    describe('func', function () {
      it('should create an Error', function () {
        const errorSpy = sinon.spy(global, 'Error');  // <= spy on the global Error
        func();
        sinon.assert.calledWithExactly(errorSpy, 'error message');  // Success!
        errorSpy.restore();
      });
    });
    

    ...最终,被测代码的孤立程度是有限的。对于像 Error 这样低级别的东西,您可能希望将其完全保持原样并使用 Chai 的 .throw 断言之类的东西来测试抛出的 Error

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-24
      • 2015-06-20
      • 2017-03-27
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多