单元测试:无法模拟承诺返回以测试我的发射
我想查看是否在promise回调中调用了发射。
这是我正在测试的代码:
"use strict";
angular.module("app.directives")
.directive("modalFilter", ["filterValidationService", function(filterValidationService) {
return {
restrict: "E",
scope: {},
templateUrl: "templates/components/modal-filter.html",
link: function(scope) {
let defaultFilter = {"size": {"to": 0, "from": 0}};
scope.clearFilter = function() {
scope.filter = defaultFilter;
};
//New - requires unit test
scope.updateTable = function() {
const tab = "availabilities";
const isFilter = scope.filter === defaultFilter ? false : true;
filterValidationService.validateSize(scope.filter.size)
.then(filterObj => {
scope.$emit("filter:cardData", filterObj, tab, isFilter);
});
};
scope.clearFilter();
}
};
}]);
这是我的单元测试:
"use strict";
describe("modal filter component:", function () {
var element;
var scope;
var mockData = {"size": {"to": 0, "from": 0}};
var mockFilteredData = {"size": {"to": 900, "from": 100}};
var filterValidationService;
beforeEach(angular.mock.module("eg.insight.services"));
beforeEach(angular.mock.module("eg.insight.directives"));
beforeEach(inject(function ($compile, $injector, $q, $rootScope, filterValidationService) {
var deferred = $q.defer();
scope = $rootScope.$new();
scope.filter = mockData;
filterValidationService = filterValidationService;
element = "<modal-filter></modal-filter>";
element = $compile(element)(scope);
angular.element(document.body).append(element);
scope.$digest();
scope = element.isolateScope();
sinon.spy(scope, "$emit");
sinon.stub(filterValidationService, "validateSize").returns(deferred.promise);
}));
it("should emit for filtered data when updateTable is called", function () {
scope.updateTable();
expect(scope.$emit.calledWith("filter:cardData", mockData.size, "availabilities", false)).toEqual(true);
});
});
我正在使用angular1与茉莉花单元测试和sinon。
我得到的错误是:“预期错误等于真”
答案 0 :(得分:1)
我想这可能是因为你在这里回复了一个承诺
sinon.stub(filterValidationService, "validateSize").returns(deferred.promise);
但是你永远不会解决这个承诺,所以永远不会调用.then()
。
也许在变量中保留承诺,并在scope.UpdateTable()
方法中it()
之后解决它。