【发布时间】:2016-11-28 15:34:39
【问题描述】:
我有一个非常简单的函数需要测试:它返回一个对象并在运行时正常工作。
此类对象的大部分字段是固定的,但其中一个字段会根据函数的结果而变化:checkWeather.getWeather().
在单元测试(Jasmine)中:checkWeather.getWeather() 被spyOn(...).andReturn(FIXEDVALUE) 监视,因此它会返回我想要的结果。但是当测试运行时,这个函数返回'NOT_INITIALIZED',这意味着它没有被初始化。但是,既然我们有 andReturn,我们就应该得到一个结果,根本不应该调用该函数;在测试期间,它应该被 FIXEDVALUE 替换。
请看代码中的cmets,也许会更清楚。
你能在测试代码中看到我的错误吗,为什么行为如此奇怪? (第一个文件完美运行,只是我需要编写单元测试,但这是行不通的)。
weather.js(在运行时正确运行)
function () {
'use strict';
angular
.module('weatherModule')
.service('TEST_ME', TEST_ME);
TEST_ME.$inject = ['FILTER_TYPE', 'checkWeather', 'values'];
function TEST_ME(FILTER_TYPE, checkWeather, values) {
// when this next is called by JASMINE, checkWeather.getWeather() returns 'NOT_INITIALIZED'
//but during testing I expect getWeather() to return VALUE as specified in .andReturn(VALUE) - see following file
console.log("checkWeather.getWeather(): ", checkWeather.getWeather());
return {
today: {
name: "today",
//Under Jasmine, the next condition will always be false
isSunny: checkWeather.getWeather() === values.SUNNY
}
};
}
})();
天气-TEST.js
'use strict';
describe('TEST_ME', function () {
var TEST_ME;
var checkWeather;
var values;
beforeEach(angular.mock.module('weatherModule'));
beforeEach(inject(function ( _TEST_ME_, _checkWeather_, _values_) {
TEST_ME = _TEST_ME_;
checkWeather = _checkWeather_;
values = _values_;
}));
describe('Not fixed parts of TEST_ME', function () {
it('should sunny', function () {
var sunToday_TEST_ME = {
isSunny: checkWeather.getWeather() === values.SUNNY
}
};
spyOn(checkWeather, 'getWeather').andReturn(values.sunToday);
//The next works!! It prints the value values.sunToday set by .andReturn()
console.log("In UT, checkWeather.getWeather(): ", checkWeather.getWeather());
expect(TEST_ME.today.isSunny).toEqual(sunToday_TEST_ME.isSunny);
}); // This fails :(
});
我写这个单元测试比写整个功能浪费了很多时间!你能看到我的错误在哪里吗?
提前谢谢你。
【问题讨论】:
-
我不太明白 checkWeather 到底是什么...在我看来,您需要一个具有 getWeather 功能的 WeatherService 之类的东西。从您提供的代码中,函数 getWeather 没有在任何地方定义,所以它总是未定义的。也许您可以分享更多代码以更好地了解您到底要测试什么
-
你真的需要两个
beforeEach()。你打算使用beforeAll()吗? -
你好,checkWeather 是一项服务,它是注入的,但也许我没有以正确的方式进行操作……无论如何,似乎“unkonwn”是此类服务可以提供的值之一返回;就像 callFake 被忽略一样。我会继续调查,也等待答案。
标签: javascript angularjs unit-testing jasmine karma-jasmine