假设我们有以下 JavaScript 代码。
object = _.isUndefined(object) ? '' : aDifferentObject.property;
我们如何能够为 Jasmine 中的任一场景编写测试?
它需要两个单独的描述吗?或者我们能否在测试本身中有一个三元条件?
谢谢!杰里米
假设我们有以下 JavaScript 代码。
object = _.isUndefined(object) ? '' : aDifferentObject.property;
我们如何能够为 Jasmine 中的任一场景编写测试?
它需要两个单独的描述吗?或者我们能否在测试本身中有一个三元条件?
谢谢!杰里米
我将像这样使用两个单独的描述
// System Under Test
function getObjectValue() {
return _.isUndefined(object) ? '' : aDifferentObject.property;
}
// Tests
describe('when object is undefined', function() {
it('should return empty string', function() {
expect(getObjectValue()).toBe('');
});
});
describe('when object is no undefined', function () {
it('should return property from different object', function () {
expect(getObjectValue()).toBe(property);
});
});
考虑以下情况(Angular JS/ES6/Jasmine,Controller 'as' 语法)
代码:
Controller.toggleWidgetView = () => {
Controller.isFullScreenElement() ? Controller.goNormalScreen() : Controller.goFullScreen();
};
Jasmine 中的测试用例:
describe('.toggleWidgetView()', function() {
it('should call goNormalScreen method', function() {
spyOn(Controller, 'isFullScreenElement').and.callFake(function(){
return true;
});
spyOn(Controller, 'goNormalScreen').and.callThrough();
Controller.toggleWidgetView();
expect(Controller.goNormalScreen).toHaveBeenCalled();
});
it('should call goFullScreen method', function() {
spyOn(Controller, 'isFullScreenElement').and.callFake(function(){
return false;
});
spyOn(Controller, 'goFullScreen').and.callThrough();
Controller.toggleWidgetView();
expect(Controller.goFullScreen).toHaveBeenCalled();
});
});
两个测试用例都通过了。基本上,我们两次调用“toggleWidgetView”方法,并且在每次调用中,条件都会发生变化(真/假),就像在现实世界中一样。