[英]Unit testing $modal with Jasmine
我有一個帶有控制器的Angular應用程序,它在函數調用期間顯示Angular-Strap
模態窗口。 它在Chrome中正常運行,但我無法進行有效的單元測試。
App模塊和FooController:
var app = angular.module("app", ["mgcrea.ngStrap"]);
app.controller("FooController", function($scope, $modal) {
var fooModal = $modal({
title: 'Foo',
content:'Bar',
show: false,
html: true,
backdrop: 'static',
placement: 'center'});
angular.extend($scope, {
makeItFoo: function() {
fooModal.show();
}
});
});
控制器規格:
describe('FooController', function () {
var scope, controller, modal;
beforeEach(module('app', function ($provide) {
// Stub out $modal service
$provide.value('$modal', function () {
return {
hide: function () { },
show: function () { }
};
});
}));
beforeEach(inject(function ($rootScope, $controller, $injector) {
//set up a new scope and the controller for the test
scope = $rootScope.$new();
controller = $controller('FooController', {$scope: scope});
modal = $injector.get('$modal');
}));
it('should show the modal', function () {
var modalSpy = spyOn(modal(), 'show');
scope.makeItFoo();
expect(modalSpy).toHaveBeenCalled();
});
});
我希望我調用makeItFoo()
來顯示模態,但Jasmine未通過測試,錯誤Expected spy show to have been called
。 我也嘗試將模態的show
屬性設置為true
而不是單獨調用show()
,並且我嘗試了其他變體來存儲$ modal服務並將其直接注入控制器,但它最終都是相同的錯誤。
我正在使用AngularJS 1.2.14,Angular-Strap 2.0.0和Jasmine 1.3.1。
而不是做這些。 使用show和hide方法為$modal
創建一個模擬對象,並設置對它們的期望。
describe('FooController', function () {
var scope, controller, modal;
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $controller) {
//set up a new scope and the controller for the test
scope = $rootScope.$new();
//Create spy object
modal = jasmine.createSpyObj('modal', ['show', 'hide']);
//provide modal as dependency to the controller.
controller = $controller('FooController', {$scope: scope, $modal:modal});
}));
it('should show the modal', function () {
scope.makeItFoo();
expect(modal.show).toHaveBeenCalled();
});
});
模態顯示是異步的。 我在http://jsfiddle.net/jwom7ns2/1/更新了你的小提琴。
更改以下部分:
it('should show the modal', function (done) {
var modalSpy = spyOn(modal(), 'show');
scope.makeItFoo();
setTimeout(function() {
expect(modalSpy).toHaveBeenCalled();
done();
});
});
當模態顯示發生時,超時包裝器等待摘要發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.