我应该如何侦察在另一个对象内调用的构造函数?

比方说,我有一个对象,有一个function,创build另一个对象作为其操作的一部分。

sinon = require('sinon') chai = require 'chai' sinonChai = require("sinon-chai") chai.use(sinonChai) chai.should() Paper = {} Paper.Origami = require('../assets/src/coffee/origami.coffee').Paper.Origami describe '#throwOrigami', -> it 'should create origami and throw it', -> m = new Monkey() throwSpy = sinon.spy(m, 'throwOrigami') createSpy = sinon.spy(Paper, 'Origami') # next function creates origami, then 'throws' it at someone m.throwOrigami(); createSpy.should.have.been.calledWithNew throwSpy.should.have.been.calledOnce 

Monkey类在Paper.Origami的顶部有一个require。

如果我在testing中创build了一个折纸,我可以通过这个testing,但是如果我把它留给Monkey对象内的创build,它将不会通过。 我怀疑这是因为两个对象的需求path不同 – 也许节点不会将它们看作是同一个对象。

问题:我可以让sinon间谍来监视Monkey对象内部的Origami对象吗?

在查看其caching之前requireparsingpath,因此path不同也无关紧要。 但是,您在testing中使用Origami属性创build了一个新的Paper对象。 因此,当你窥探Paper, 'Origami' ,它就是你在testing文件中创build的Paper对象的属性Origami ,它被一个间谍替代。 我想你可以做下面的事情:

 Paper = require('../assets/src/coffee/origami.coffee').Paper 

如果你现在改变了Paper对象,它将和你在Monkey模块中使用的一样。 不过,我会build议使用像proxyquire的东西间谍或嘲笑依赖。