jeudi 6 juillet 2017

How to test object from factory with mocha with sinon

Background

I have a factory function that creates dogs that bark:

const dogFactory = () => {
    const bark = name => console.log(`${name} just barked!`);

    return{
        bark
    };
}; 

One would use it like:

const dog = dogFactory();
dog.bark("boby"); //"boby just barked!"

I also have an hotel of dogs. Business is not going good, so to keep appearances I am creating my own dogs ! This hotel thus takes a dogFactory as an argument and looks like the following:

const dogHotel = deps => {
    const {
        dogFactory
    } = deps;

    let dogsHosted = [];

    const feed = () => {
        dogsHosted.push(dogFactory());
        dogsHosted.forEach( (dog, i) => dog.bark(i));
    }

    return{
        feed
    };  
};

You would use it like:

const hotelAwsome = dogHotel({dogFactory: dogFactory});
hotelAwsome.feed();

This hotel feeds dogs. Because there is no business it creates a dog and then feeds everyone. Every time a dog is fed, it barks of happiness!

Problem

One would think that creating infinite dogs in a broken hotel would be the problem, but that is not the case!

The problem here is that I want to make sure the dogs are happy barking. That is, that for each dog in the hotel bark is being called.

Code

This is currently my test. I am using mocha as a test suite, I am using sinon to spy on my fake factory objects:

const sinon = require( "sinon" );
const chai = require( "chai" );
const expect = chai.expect;

describe("dog hotel", () => {

    const fakeFacory = () => {
        const bark = () => sinon.spy()
        return {bark};
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();
        //expect something here 
    });
});

The issue here is that I am passing a fake dog factory, but I can't check with sinon if the dog are barking or not!

Question

How do I test if the dogs that are created in the hotel, are barking?

Aucun commentaire:

Enregistrer un commentaire