背景
我有一个工厂的功能,创造狗叫:
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
});
});
这里的问题是,我是经过一个假狗工厂,但我不能检查是否狗叫!
问题
我该如何测试在酒店里被创造出来的狗是否在吠叫?
发布于 2017-07-06 12:58:15
你应该把间谍从假工厂搬出去。现在,您只需在expect中使用间谍属性 (callOnce,calls)。
Kudos关于有趣的问题:)
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);
});
});
https://stackoverflow.com/questions/44949360
复制相似问题