我正在使用Jest框架,并试图实现一个函数的模拟。我有一个小型机场应用程序,允许用户起飞和降落飞机,但它必须受到限制,因为随机天气。
天气属于另一个类别,并且是随机的,对于我的测试,我需要模拟天气函数,以便在一个测试中总是返回true,而在其他测试中返回false。
我遇到的困难是如何准确地实现模拟函数?文档中谈到使用jest.fn并将其设置为常量变量,但这使我感到困惑,因为我不理解jest.fn如何在函数名称不提供的情况下等同于函数。更有趣的模拟文档,虽然是全面的,但对于学习的人来说有点难以访问,而我所拥有的大多数其他资源也会导致同样的混乱。从本质上说,我希望有一个外行的术语指南来实现这一点?例如-
测试:
const Airport = require('./airport')
const Plane = require('./plane')
const Weather = require('./weather')
airport = new Airport('Bristol')
plane = new Plane('Boeing 747')
test('the airport lands a plane', () => {
expect(airport.land(plane)).toBe(1);
});
test('the airport allows a plane to take off', () =>{
expect(airport.takeOff()).toBe(0);
});
test('the airport has a default capacity of 1 when constructed', () => {
bath = new Airport('Bath')
expect(bath.capacity).toBe(1)
})
test('The airports default capacity can be defined at construction', () => {
bristol = new Airport('Bristol', 5)
expect(bristol.capacity).toBe(5)
});
test("The airport doesn't let you land when the hangar is full", () => {
wells = new Airport('Wells', 1)
plane2 = new Plane('Spitfire')
wells.land(plane)
expect(wells.land(plane2)).toBe('HANGAR FULL LANDING DENIED')
});
test("The airport doesn't let you land when weather is stormy", () =>{
york = new Airport('york', 1)
// york.weather = true
plane = new Plane('plane')
expect(york.land(plane)).toEqual('LANDING DENIED POOR WEATHER')
});正在测试的机场档案:
const Weather = require('./weather')
class Airport {
constructor(name, capacity = 1, weather = new Weather) {
this.name = name;
this.hangar = [];
this.capacity = capacity;
this.weather = weather.getWeather();
}
land (plane) {
if (this.weather === true) {
return 'LANDING DENIED POOR WEATHER'
} else if (this._isFull() === false) {
this.hangar.push(plane)
return this.hangar.length
} else {
return 'HANGAR FULL LANDING DENIED'
}
};
takeOff () {
this.hangar.pop()
return this.hangar.length;
};
_isFull () {
if (this.hangar.length < this.capacity) {
return false
} else {
return true
}
};
};
module.exports = Airport;具有随机天气功能的天气等级:
class Weather {
getWeather() {
var chance = Math.floor(Math.random() * 10)
if (chance <= 3) { return true } else { return false }
}
}
module.exports = Weather;您可以在文件中看到,我发现了一种覆盖天气的糟糕方法,通过手动将机场中的属性设置为true,我被告知这是一种代码气味,并且希望重构到一个适当的模拟函数/模块/类。
发布于 2019-01-22 05:25:26
您的Airport类被设置为使用依赖注入获取天气信息。
它将对传递给构造函数的第三个参数调用getWeather (如果没有提供,则调用Weather的新实例),以设置Airport的天气。
您可以使用此依赖项注入来提供Weather依赖项的模拟实现,以设置测试所需的天气:
test("The airport doesn't let you land when weather is stormy", () =>{
const york = new Airport('york', 1, { getWeather: () => true }) // always bad weather
const plane = new Plane('plane')
expect(york.land(plane)).toEqual('LANDING DENIED POOR WEATHER') // SUCCESS
});https://stackoverflow.com/questions/54289118
复制相似问题