使用QUnit测试Angular.js.

时间:2014-03-18 07:39:30

标签: javascript angularjs unit-testing qunit

如何将angular.mock.inject()与QUnit(而不是Jasmine)一起使用?

以下代码定义angular.mock.dump,但angular.mock.injectundefined

<!DOCTYPE html>
<html ng-app="mymodule">
  <head>
    <meta charset="utf-8">
    <script src="http://code.angularjs.org/1.2.4/angular.js"></script>
    <script src="http://code.angularjs.org/1.2.4/angular-mocks.js"></script>
    <script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
    <link href="http://code.jquery.com/qunit/qunit-1.14.0.css" rel="stylesheet"> 
    <script>
      angular.module( "mymodule", [ "ngMock" ] );
    </script>
  </head>
  <body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

我查看了Angular源代码,除非使用Jasmine或Mocka,否则angular.mock.injectangular.mock.module似乎都未定义。

问题的解决方案似乎是为每个测试用例手动创建一个注入器,或者手动修补angular-mocks.js以使其测试框架不可知(这应该是恕我直言):

--- angular-mocks.js    2014-03-19 07:12:40.194522300 +0100
+++ angular-mocks2.js   2014-03-19 07:12:32.344002500 +0100
@@ -1917,11 +1917,24 @@


-if(window.jasmine || window.mocha) {
+if ( window.jasmine || window.mocha || window.QUnit ) {

   var currentSpec = null,
       isSpecRunning = function() {
-        return currentSpec && (window.mocha || currentSpec.queue.running);
+        if ( window.mocha ) {
+          return currentSpec && true;
+        } else if ( window.jasmine ) {
+          return currentSpec && currentSpec.queue.running;
+        } else if ( window.QUnit ) {
+          return currentSpec && currentSpec.config.queue.length > 0;
+        }
       };

+  if ( window.QUnit ) {
+    var beforeEach = testStart;
+    var afterEach = testDone;
+    var modulefunction = "ngmodule";
+  } else {
+    var modulefunction = "module";
+  }

   beforeEach(function() {
@@ -1974,5 +1987,5 @@
    *        the module name and the value being what is returned.
    */
-  window.module = angular.mock.module = function() {
+  window[modulefunction] = angular.mock.module = function() {
     var moduleFns = Array.prototype.slice.call(arguments, 0);
     return isSpecRunning() ? workFn() : workFn;