gpt4 book ai didi

javascript - AngularJS $window : how can it be beneficial in unit testing?(与使用 window 相比)

转载 作者:行者123 更新时间:2023-12-03 02:54:27 24 4
gpt4 key购买 nike

虽然官方文档说,

While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

我还是无法理解它。 😕 我如何从单元测试代码中的 $window 中受益?在下面的代码片段中,我可以监视/模拟并使用 native 窗口对象,无论是否有 $window。它是如何导致可测试性问题的?

angular.module('messagePopper', [])
.factory('popper', function popperFactory($window) {
return {
popupMessage(message) {
alert(message);
},

popupMessageWith$window(message) {
$window.alert(message);
}
};
});

describe('messagePopper: popper service', () => {
let $injector;
let $window;
let popper;

beforeEach(() => {
module('messagePopper');

inject((_$injector_) => {
$injector = _$injector_;
$window = $injector.get('$window');
popper = $injector.get('popper');
});
});

it('should popupMessage correctly', () => {
const message = 'welcome glenn@foodie.net';

const alertMock = spyOn(window, 'alert');

popper.popupMessage(message);

expect(alertMock)
.toHaveBeenCalledWith(message);
});

it('should popupMessageWith$window correctly', () => {
const message = 'welcome glenn@foodie.net';

const alertMock = spyOn($window, 'alert');

popper.popupMessageWith$window(message);

expect(alertMock)
.toHaveBeenCalledWith(message);
});
});

在这里摆弄:https://jsfiddle.net/glenn/x42uex66 .

最佳答案

虽然使用全局窗口对象有效,但有时测试可能会失败,导致无法清理窗口对象以进行下一次测试。在这种情况下,您会突然看到许多测试似乎无缘无故地失败,而不仅仅是导致问题的一个测试。

关于javascript - AngularJS $window : how can it be beneficial in unit testing?(与使用 window 相比),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com