【问题标题】:how should I spy on a constructor that is called inside of another object?我应该如何监视在另一个对象内部调用的构造函数?
【发布时间】:2013-02-18 18:30:52
【问题描述】:

假设我有一个对象,该对象具有创建另一个对象作为其操作的一部分的函数。

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 的要求。

如果我在测试中创建一个 Origami,我可以通过这个测试,但如果我将它留给 Monkey 对象内部的创建,它就不会通过。我怀疑这是因为两个对象之间的要求路径不同——也许节点不会将它们视为同一个对象。

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

【问题讨论】:

    标签: node.js testing coffeescript sinon


    【解决方案1】:

    require 在查看其缓存之前解析路径,因此路径不同并不重要。但是,您在测试中创建了一个具有Origami 属性的新Paper 对象。因此,当您监视Paper, 'Origami' 时,它是您在测试文件中本地创建的Paper 对象的属性Origami,它被替换为间谍。我想您可以改为执行以下操作:

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

    如果您现在更改 Paper 对象,它将与您在 Monkey 模块中使用的相同。不过,我建议使用 proxyquire 之类的东西来监视或模拟依赖项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2017-12-22
      • 1970-01-01
      • 2018-08-10
      • 2010-09-22
      相关资源
      最近更新 更多