简体   繁体   中英

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. I have a Backbone App (AMD/requirejs driven) and I use Mocha (Sinon, Chai, ...) for BDD testing - this basically wraps up my setup.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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