代码之家  ›  专栏  ›  技术社区  ›  srgbnd

存根在另一个对象构造函数中的对象

  •  1
  • srgbnd  · 技术社区  · 6 年前

    如何存根 this.desires.eat ?

    const sinon = require('sinon');
    const expect = require('expect.js');
    
    class Cat {
      constructor() {
        this.desires = {
          eat: () => 'for a mouse'
        }
      }
    
      breakfast() {
        return 'go ' + this.desires.eat();
      }
    }
    
    const twinky = new Cat();
    
    sinon.stub(twinky, 'desires.eat', () => {
      return 'fishing';
    });
    
    describe('test cat', () => {
      it('cat is going to have breakfast', (done) => {
        const solution = twinky.breakfast();
        expect(solution.includes('fishing')).to.be(true);
        done();
      });
    });
    

    /media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/util/core.js:115
                        throw error;
                        ^
    
    TypeError: Attempted to wrap undefined property desires.eat as function
        at Object.wrapMethod (/media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/util/core.js:106:29)
        at Object.stub (/media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/stub.js:67:26)
        at Object.<anonymous> (/media/trex/safe1/Development/app/server/lib/test.js:19:7)
        at Module._compile (module.js:652:30)
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
        at tryModuleLoad (module.js:505:12)
        at Function.Module._load (module.js:497:3)
        at Function.Module.runMain (module.js:693:10)
        at startup (bootstrap_node.js:191:16)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   T.J. Crowder    6 年前

    the docs 它看起来像:

    sinon.stub(twinky.desires, 'eat', () => {
        return 'fishing';
    });
    

    例如,由于方法是打开的 twinky.desires ,把它传过来,而不是 twinky eat 作为方法名。显然,sinon不会解析虚线符号字符串并深入到对象中(这对于它来说是完全合理的)。