存根另一个对象构造函数内部的对象

时间:2018-09-28 14:07:00

标签: javascript sinon

如何对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 个答案:

答案 0 :(得分:1)

the docs中,它看起来像:

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

例如,由于该方法位于twinky.desires上,因此传入而不是twinky,然后只需传递eat作为方法名称即可。显然,sinon不会解析点号表示的字符串并深入到对象中(这样做是完全合理的)。