Angular 1/ui-select/Jasmine - 测试元素(如果存在于 ng-if 中)



我想测试ng-if内输入是否存在,如果没有ng-如果测试完美通过,但不能使用ng-if

在我的模板中,我有:

<div ng-if="$ctrl.doShowAir">
<input class="form-control" type="text">
</div>

doShowAir是函数doShow()中的一个变量,在以前的 ui-select 中选择选项时应true该变量

<ui-select ng-model="$ctrl.parking.parkingType"
on-select="$ctrl.doShow()">
<ui-select-match>
<span>{{ $select.selected.label }}</span>
</ui-select-match>
<ui-select-choices repeat="item in $ctrl.projectReferences.parkingType | filter: { label: $select.search }">
<span ng-bind-html="item.label"></span>
</ui-select-choices>
</ui-select>

功能:

doShow() {
this.doShowAir = (this.parkingType.labelKey === 'parking_type.air')
}

和单元测试:

import angular from 'angular'
import 'angular-mocks'
let scope
let rootScope
let compile
let htmlElement
let ctrl
fdescribe('projectExteriorParking', () => {
beforeEach(() => {
angular.mock.module('ProjectExteriorParkingModule')
angular.mock.module('ui.select')
})
beforeEach(inject((_$compile_, _$rootScope_) => {
rootScope = _$rootScope_
compile = _$compile_
scope = rootScope.$new()
scope.parking = {}
htmlElement = compile(`<project-exterior-parking parking="project.realEstateProjectProduct.parkings"></project-exterior-parking>`)(scope)
rootScope.$digest()
}))
beforeEach(inject(($componentController) => {
let bindings = {
parking: {},
projectReferences: {}
}
ctrl = $componentController('projectExteriorParkingModule', null, bindings)
}))
it('should contain two input', () => {
const inputItems = htmlElement.get(0).querySelectorAll('input')
expect(inputItems.length).toBe(2)
})
})

如何模拟变量shouldShowAir为真,或模拟调用函数的 ui-select 上的选择on-select="$ctrl.doShow()"因为我无法访问doShow()函数。 或者如何"手动"将输入添加到测试中并编译它以及<project-exterior-parking parking="project.realEstateProjectProduct.parkings"></project-exterior-parking>

获取已编译元素的控制器,您调用ctrl = htmlElement.controller('directive|component name')

在您的情况下ctrl = htmlElement.controller('projectExteriorParking')

directive|component是将组件或指令注册到angular.module时提供的字符串

知道如何从编译的 htmlElement 中获取控制器,您现在可以调用ctrl.doShow()$rootScope.$apply()然后断言元素以您在测试中的方式呈现

代码中还有其他一些内容:ng-model="$ctrl.parking.parkingType"

doShow() {
// ngModel is this.parking.parkingType
// is there this.parkingType or is this a mistake?
this.doShowAir = (this.parkingType.labelKey ===  'parking_type.air')
}

传递给 $compile 的范围缺少必需绑定:

beforeEach(inject((_$compile_, _$rootScope_) => {
rootScope = _$rootScope_
compile = _$compile_
scope = rootScope.$new()
scope.parking = {}
// The compiled element has `parking` bound to `project.realEstate...` yet you don't have it on scope
// you should assign some mock data as `scope.project = { realEstateProjectProduct }`
htmlElement = compile(`<project-exterior-parking parking="project.realEstateProjectProduct.parkings"></project-exterior-parking>`)(scope)
rootScope.$digest()

}((

您应该传递一些模拟数据,或者将ctrl.parkingType设置为您希望会使方法ctrl.doShow()设置为 true 的值ctrl.doShowAir

相关内容

最新更新