【发布时间】:2015-02-09 06:29:29
【问题描述】:
我目前正在编写一个服务来控制上传流程。我现在正在为显示和隐藏上传模式框的功能编写单元测试。在测试中,我使用angular.element.find 来查看模态是否存在。在第二个测试中,这个数字比我预期的要高,好像它没有重置一样。
两个测试如下:
describe('show', function() {
it('should initially not show the modal', function() {
expect(upload.isShowing()).toEqual(false);
expect(angular.element.find('.modal').length).toEqual(0);
});
it('should show the upload modal', function() {
expect(upload.isShowing()).toEqual(false);
expect(angular.element.find('.modal').length).toEqual(0);
upload.show();
$rootScope.$digest();
expect(upload.isShowing()).toEqual(true);
expect(angular.element.find('.modal').length).toEqual(1);
});
});
describe('cancel', function() {
it('should hide the upload form', function() {
expect(upload.isShowing()).toEqual(false);
expect(angular.element.find('.modal').length).toEqual(0);
upload.show();
$rootScope.$digest();
expect(upload.isShowing()).toEqual(true);
expect(angular.element.find('.modal').length).toEqual(1);
});
});
第一个描述块通过正常,但第二个失败。它告诉我它Expected 1 to equal 0. 如果我在cancel 的测试中用angular.element.find 注释掉第一个期望,它会说“期望2 等于1。”
我所能确定的是,html 都被扔进了同一个空间,并且在每次测试后都在复合。有什么方法可以防止这种行为,或者使用 `afterEach' 语句来刷新以前的 HTML?
谢谢!
修正
如果有帮助,这里是这套测试的完整代码:
describe('uploadService', function() {
var $rootScope,
upload;
beforeEach(module('upload'));
beforeEach(module('upload.service'));
beforeEach(module('bublNg.templates'));
beforeEach(module('ui.bootstrap.tpls'));
beforeEach(inject(function($injector) {
upload = $injector.get('upload');
$rootScope = $injector.get('$rootScope');
}));
describe('isShowing', function() {
it('should return true if the modal us showing', function() {
expect(upload.isShowing()).toEqual(false);
upload.show();
expect(upload.isShowing()).toEqual(true);
});
});
describe('show', function() {
it('should initially not show the modal', function() {
expect(upload.isShowing()).toEqual(false);
expect(angular.element.find('.modal').length).toEqual(0);
});
it('should show the upload modal', function() {
expect(upload.isShowing()).toEqual(false);
expect(angular.element.find('.modal').length).toEqual(0);
upload.show();
$rootScope.$digest();
expect(upload.isShowing()).toEqual(true);
expect(angular.element.find('.modal').length).toEqual(1);
});
});
describe('cancel', function() {
it('should hide the upload form', function() {
expect(upload.isShowing()).toEqual(false);
// expect(angular.element.find('.modal').length).toEqual(0);
upload.show();
$rootScope.$digest();
expect(upload.isShowing()).toEqual(true);
// expect(angular.element.find('.modal').length).toEqual(1);
upload.cancel();
expect(upload.isShowing()).toEqual(false);
});
});
});
【问题讨论】:
标签: javascript angularjs unit-testing angular-ui-bootstrap angularjs-service