更新答案:
您说得对,将所有内容导入单个文件时,事情并没有按预期工作。
深入研究你似乎遇到了 Babel/Jest 为支持依赖全局变量(如 AngularJS)的浏览器脚本所做的一些魔法。
发生的情况是您模块的 angular 变量不与 angular-mocks 可见的全局 angular 变量相同。
您可以通过在您的一个测试的顶部运行它来检查这一点:
import * as angular from 'angular'
import 'angular-mocks'
console.log(angular === window.angular); // `false` in Jest!
console.log(angular.mock); // undefined
console.log(window.angular.mock); // `{...}` defined
要解决此问题,您只需在测试中使用全局 angular 变量。
src/__test__/all-in-one.test.js:
import "angular";
import "angular-mocks";
/*
Work around Jest's window/global mock magic.
Use the global version of `angular` that has been augmented by angular-mocks.
*/
var angular = window.angular;
export var app = angular.module('app', []);
app.directive('myDirective', () => ({
link: (scope, element) => {
console.log('This does log');
scope.content = 'Hi!';
},
template: 'content: {{content}}'
}));
describe('myDirective', function(){
var element;
var scope;
beforeEach(function(){
angular.mock.module(app.name);
});
it('should do something', function(){
inject(function(
$rootScope,
$compile
){
scope = $rootScope.$new();
element = $compile('<my-directive></my-directive>')(scope);
scope.$digest();
});
expect(element.html()).toEqual('content: Hi!');
});
});
原始答案:(之所以有效,是因为我在测试中不小心使用了angular 的全球版本。)
测试中的 Angular 模块未在您的测试中正确初始化。
您对beforeEach(app) 的调用不正确。
您需要使用angular.mock.module("moduleName") 来初始化您的模块。
describe('myDirective', () => {
var element, scope
// You need to pass the module name to `angular.mock.module()`
beforeEach(function(){
angular.mock.module(app.name);
});
// Then you can set up and run your tests as normal:
beforeEach(inject(($rootScope, $compile) => {
scope = $rootScope.$new()
element = $compile('<my-directive></my-directive>')(scope)
scope.$digest()
}))
it('should actually do something', () => {
expect(element.html()).toEqual('Hi!')
})
});
然后你的测试对我来说就像预期的那样:
PASS src\__test__\app.test.js
myDirective
√ should do something (46ms)
作为参考,这里是完整的应用和测试:
src/app/app.module.js:
import * as angular from 'angular'
export var app = angular.module('app', []);
app.directive('myDirective', () => ({
link: (scope, element) => {
console.log('This does log');
scope.content = 'Hi!';
},
template: 'content: {{content}}'
}))
src/__test__/app.test.js:
import {app} from "../app/app.module";
import "angular-mocks";
describe('myDirective', function(){
var element;
var scope;
beforeEach(function(){
angular.mock.module(app.name);
});
beforeEach(inject(function(
$rootScope,
$compile
){
scope = $rootScope.$new();
element = $compile('<my-directive></my-directive>')(scope);
scope.$digest();
}));
it('should do something', function(){
expect(element.html()).toEqual('content: Hi!');
});
});