lundi 29 août 2016

Unit testing that a function has been called in a factory object creation

I m building applications with TDD, and I m now facing a problem that I've never encountered. I m using Mocha, Chai, Chai-spies, and nodejs in v4.5.0

I need to make this test passing :

  it('should call the implicit.deserialize() method', () => {
      const implicit = StrategyFactory.create('implicit')
      const spy = chai.spy.on(implicit, 'deserialize')
      expect(spy).to.have.been.called.once
    })

It's clear that this test doesn't have any sense. I m trying to spy on the item that my factory creates, to check if I m calling the good methods inside of it. But it's a synchronous code, so the code inside of the factory will be executed before I create my spy.

This test should drive me to the following implementation :

static create (name) {
    if (name === Constants.STRATEGY_IMPLICIT) {
      const implicit = new Implicit(oauth2orize.createServer(), new AuthService())
      implicit.deserialize() // How can I test that line ?
      return implicit
    }
    throw new Error(Constants.STRATEGY_NOT_FOUND)
  }

So, as you can see, I m trying to spy on the implicit.deserialize method. And I don't have any idea how to make the test passing.

Any ideas ?

Thanks for your help

Aucun commentaire:

Enregistrer un commentaire