gpt4 book ai didi

javascript - 为什么这个 Angular 指令没有在 Jasmine 单元测试中编译?

转载 作者:搜寻专家 更新时间:2023-11-01 04:30:16 25 4
gpt4 key购买 nike

先决条件:我正在使用 Karma 对我的 Angular.js 应用模块运行 Jasmine 单元测试。

我的应用使用以下模式来公开模块(服务/指令/ Controller ):

simple.js

'use strict';

export default (angular) => {
angular.module('simple', [])
.directive('simple', [function() {
return {
restrict: 'E',
replace: true,
template: '<h1>COMPILED!</h1>'
};
}]);
};

上面例子对应的单元测试是这样的:

simple.test.js

import angular from 'angular';
import mocks from 'angular-mocks';
import simpleModule from './simple';

describe('simple', () => {
var $compile,
$rootScope;

// Load the simple module, which contains the directive
beforeEach(() => {
let simpleComponent = new simpleModule(angular);
// module('simple') raises a TypeError here
// I have also tried angular.module('simple') which
// I am pretty sure is incorrect.
});

// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject((_$compile_, _$rootScope_) => {
// The injector unwraps the underscores (_) from around the
// parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));

it('Replaces the element with the appropriate content', () => {
// Compile a piece of HTML containing the directive
var element = angular.element("<simple>not compiled</simple>");

var compiledElement = $compile(element)($rootScope);

// fire all the watches, so the scope expressions evaluate
$rootScope.$digest();

// Check that the compiled element contains the templated content
expect(element.html()).toContain("COMPILED!");

});

});

问题:在网络浏览器中使用 Karma 运行上述测试时,测试失败并且元素似乎没有被编译。

我错过了什么?

最佳答案

我可以在您的代码中看到,您在执行 $compile 之前缺少新的 $scope 的创建。你应该这样做:

it('Replaces the element with the appropriate content', () => {
// Compile a piece of HTML containing the directive
var scope = $rootScope.$new(); // create a new scope
var element = angular.element("<simple>not compiled</simple>");
var compiledElement = $compile(element)(scope);

// fire all the watches, so the scope expressions evaluate
scope.$digest();

// Check that the compiled element contains the templated content
expect(element.html()).toContain("COMPILED!");
});

关于javascript - 为什么这个 Angular 指令没有在 Jasmine 单元测试中编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35951453/

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