gpt4 book ai didi

javascript - stub 一个对象,它在另一个对象构造函数中

转载 作者:行者123 更新时间:2023-11-30 20:09:22 25 4
gpt4 key购买 nike

如何 stub 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)

最佳答案

来自 the docs它看起来像:

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

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

关于javascript - stub 一个对象,它在另一个对象构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com