我如何使用摩卡测试AngularJS code? [英] How do I test AngularJS code using Mocha?

查看:153
本文介绍了我如何使用摩卡测试AngularJS code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我十分赞同摩卡(书面数千单元测试)经验,我很新的AngularJS(笔试只是我的第一个项目)。

Basically, I'm quite experienced with Mocha (written thousands of unit tests), and I'm quite new to AngularJS (written just my first project).

现在我怎样,我可能用摩卡单元测试所有的东西AngularJS疑惑。

Now I am wondering how I might unit test all the AngularJS stuff using Mocha.

我知道,摩卡在浏览器中运行,而且我已经做到了这一点。但我怎么构造和设置的东西呢?

I know that Mocha runs in the browser, and I have already done this. But how do I structure and setup things?

我想我需要:


  • 加载AngularJS

  • 加载摩卡

  • 加载我的测试

在每一个测试中,我需要加载控制器,服务,...进行测试。我怎么做?我不使用require.js或类似的东西,该文件与主要包含以下内容只是脚本文件:

Within each of the tests, I need to load a controller, a service, ... to test. How do I do that? I am not using require.js or something like that, the files are just script files with basically the following content:

angular.controller('fooController', [ '$scope', function ($scope) {
  // ...
}]);

我如何引用和测试中实例化控制器?
同样的服务,指令成立,...

How do I reference and instantiate that controller within a test? The same holds true for services, directives, ...

我是否需要创建一个 $范围嘲笑 $ HTTP &安培;合。为我自己,或者是有一些帮助呢?

Do I need to create mocks for $scope, $http & co. for myself, or is there some help?

请注意,我知道有噶测试运行(原名Testacular),但我并不想完全切换我的测试运行。

Please note that I am aware that there is the Karma test runner (formerly known as Testacular), but I do not want to switch my test runner completely.

推荐答案

这样做的一个方法是使用 $注射器 在你的测试:

One way of doing that is to use Angular $injector in your tests:

myModule_test.js

suite('myModule', function(){
  setup(function(){
    var app = angular.module('myModule', []);
    var injector = angular.injector(['myModule', 'ng']);
    var service = injector.get('myService');
  });

  suite('myService', function(){
    test('should return correct value', function(){
       // perform test with an instance of service here
    });
  });
});

HTML 应类似于此:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>myModule tests</title>
  <link rel="stylesheet" media="all" href="vendor/mocha.css">
</head>
<body>
  <div id="mocha"><p><a href=".">Index</a></p></div>
  <div id="messages"></div>
  <div id="fixtures"></div>
  <script src="vendor/mocha.js"></script>
  <script src="vendor/chai.js"></script>
  <script src="angular.min.js"></script>
  <script src="myModule.js"></script>
  <script>mocha.setup('tdd')</script>
  <script src="myModule_test.js"></script>
  <script>mocha.run();</script>
</body>
</html>

这篇关于我如何使用摩卡测试AngularJS code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆