简体   繁体   English

使用Java中的间谍(Jasmine / Mocha)在方法中测试类实例化

[英]Test class instanciation within a method using a spy in Javascript (Jasmine/Mocha)

I am currently starting to test my javascipt code and I now have a problem I am not able to solve. 我目前正在测试我的javascipt代码,但现在有一个我无法解决的问题。 I have a Backbone App (AMD/requirejs driven) and I use Mocha (Sinon, Chai, ...) for BDD testing - this basically wraps up my setup. 我有一个Backbone应用程序(由AMD / requirejs驱动),我使用Mocha(Sinon,Chai等)进行BDD测试-这基本上完成了我的设置。

Let's say we are talking about this class 假设我们正在谈论这堂课

class MyApp extends App
    init: ->
        @initcontrollers()

    initControllers: ->
        new HeaderController()
        new NavController()

To the the first method init , I can write the following testcase 对于第一个方法init ,我可以编写以下测试用例

before ...

describe 'init', ->

    it 'should call @initControllers', ->
        spy = sinon.spy(@myInstance, 'initControllers')
        @myInstance.init()
        expect(spy.called).toBeTruthy()

this works pretty good. 这个效果很好。 but now I'd like to test, if the second method initControllers actually creates new instances of HeaderController and NavController 但现在我想测试一下,如果第二种方法initControllers实际创建的新实例HeaderControllerNavController

How can I achieved that? 我该如何实现? I am stuck with that right now and I am a little bit confused because I start thinking of it not to be the right way to call those controllers. 我现在仍然坚持这一点,我有点困惑,因为我开始认为这不是调用这些控制器的正确方法。

Any help appreciated 任何帮助表示赞赏

I was really confused, but @mu-is-to-short probably gave me the right hint 我真的很困惑,但是@ mu-is-to-short可能给了我正确的提示

I did it like this now: 我现在是这样的:

describe '@initControllers', ->
    it 'should call HeaderController', ->
        headerController = new HeaderController()
        spy = sinon.spy(headerController.__proto__, 'initialize')
        @myInstance.initControllers()
        expect(spy.calledOnce).toByTruthy()

It works for me, would that be the right approach? 它对我有用,这是正确的方法吗? Thanks anyway 不管怎么说,还是要谢谢你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM