【问题标题】:How to test object from factory with mocha with sinon如何用 mocha 和 sinon 从工厂测试对象
【发布时间】:2017-12-10 11:42:24
【问题描述】:

背景

我有一个工厂函数可以创建会吠的狗:

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

    return{
        bark
    };
}; 

人们会像这样使用它:

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

我还有一家狗旅馆。生意不好,所以为了保持形象,我正在创造自己的狗!因此,这家酒店将dogFactory 作为参数,如下所示:

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

    let dogsHosted = [];

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

    return{
        feed
    };  
};

你会像这样使用它:

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

这家酒店喂狗。因为没有生意,它创造了一条狗,然后喂给所有人。每次喂狗,它都会发出快乐的叫声!

问题

有人会认为在破旧的酒店里创造无限的狗会是个问题,但事实并非如此!

这里的问题是我想确保狗高兴地吠叫。也就是说,对于酒店中的每条狗bark 正在被调用。

代码

这是我目前的测试。我使用mocha 作为测试套件,我使用sinon 来监视我的假工厂对象:

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 
    });
});

这里的问题是我路过一家假狗工厂,但我无法检查狗是否在吠叫!

问题

如何测试在酒店创建的狗是否在吠?

【问题讨论】:

    标签: javascript unit-testing testing mocha.js sinon


    【解决方案1】:

    您应该将间谍作品移出假工厂。现在你可以在 expect 中使用 spy properties (callOnce, calls)。

    感谢这个有趣的问题:)

    describe("dog hotel", () => {
        const spy = sinon.spy(); // create the spy outside
    
        const fakeFacory = () => {
            return {
              bark: spy // assign it to bark
            };
        };
    
        it("should make the dogs bark with happiness when feeding them!", () => {
            const hotelAweomse = dogHotel({dogFactory: fakeFacory});
            hotelAwesome.feed();
    
            // expect only one bark
            expect(spy.calledOnce).to.be.true;
    
            // expect a number of barks
            expect(spy.calls).to.equal(1);
        });
    });
    

    【讨论】:

    • 好主意,谢谢!我必须等待 39 秒才能接受 xD
    • 这家狗旅馆的服务很糟糕。你必须等待和等待:)
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多