gpt4 book ai didi

javascript - Angular JS + Jasmine 测试 Controller

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:45:45 26 4
gpt4 key购买 nike

我在 controllersSpec.coffee Angular App 代码中有一个简单的测试:

describe 'Controllers', ->
beforeEach ->
angular.module 'app'
describe 'MainCtrl', ->
beforeEach inject ($controller, $rootScope) ->
scope = $rootScope.$new()
ctrl = $controller 'MainCtrl', $scope: scope
it 'should be true', ->
expect(true).toEqual(true)

和用于测试的 SpecRunner.html 文件:

<html lang="eu">
<head>
<title>Angular Test Runner</title>
<script src="../js/libs/jquery.js"></script>
<script src="lib/jasmine.js"></script>
<script src="lib/jasmine-html.js"></script>
<script src="../js/libs/underscore.js"></script>
<script src="../js/libs/angular.js"></script>
<script src="lib/angular/angular-mocks.js"></script>
<script src="lib/angular/angular-scenario.js" ng-autotest></script>
<script src="../js/controllers.js"></script>
<script src="controllersSpec.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>

抛出错误,关于 angular-mock 中的“$modules”:

TypeError: Cannot read property '$modules' of null
at Object.workFn (http://localhost/lolobot/test/lib/angular/angular-mocks.js:1745:25)
at Object.<anonymous> (http://localhost/lolobot/test/lib/angular/angular-scenario.js:24673:54)
at Array.forEach (native)
at Object.forEach (http://localhost/lolobot/test/lib/angular/angular-scenario.js:9538:11)

你能帮我解决这个问题吗?这是我的第一个测试 Angular 应用程序。

最佳答案

我认为您需要包含更多 Angular 包。我将整个套件包括在我的运行者中。我不认为我真的需要它们,但我试图删除一些但失败了。具体来说,我有这些:

angular.js
angular-bootstrap.js
angular-cookies.js
angular-loader.js
angular-mocks.js
angular-resource.js
angular-sanitize.js

此外,在您的测试中,您可能希望拥有

controller = null
scope = null

在您的 describe block 中的任何其他内容之前。否则,您的 Controller 和作用域最终会成为 inject 函数中的局部变量。

关于javascript - Angular JS + Jasmine 测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820644/

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