使用PouchDB设置karma单元测试

4
我想为使用pouchdb + angular-pouchdb的angular应用程序设置单元测试。但是当我运行以下命令时:karma start karma.conf.js,我收到以下错误信息:

PhantomJS 1.9.7 (Mac OS X) ERROR

TypeError: 'undefined' is not a function (evaluating 'eventEmitter[method].bind(eventEmitter)')

at .../public/bower_components/pouchdb/dist/pouchdb-nightly.js:5758

该angular应用程序在浏览器中正常运行,并且我的karma.conf.js文件包含相同的依赖项,因此我不明白为什么pouchdb-nightly.js会有一个未定义的函数。我错过了什么?

bind 在 phantomjs 中未实现。我不熟悉 karma,无法推荐解决方案。 - Artjom B.
".bind被PouchDB库调用。这意味着PouchDB不支持PhantomJs浏览器吗?" - vilsbole
2个回答

9
这是一个常见的错误:PhantomJS没有实现Function.prototype.bind(这里是问题),所以你需要使用es5-shim库。

或者你可以只使用Function.prototype.bind的shim,而不是包含整个es5-shim库。这里有一个示例(取自这里):

(function () {
  'use strict';
  // minimal polyfill for phantomjs; in the future, we should do ES5_SHIM=true like pouchdb
  if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
      if (typeof this !== "function") {
        // closest thing possible to the ECMAScript 5
        // internal IsCallable function
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
      }

      var aArgs = Array.prototype.slice.call(arguments, 1),
          fToBind = this,
          fNOP = function () {},
          fBound = function () {
            return fToBind.apply(this instanceof fNOP && oThis
                   ? this
                   : oThis,
                   aArgs.concat(Array.prototype.slice.call(arguments)));
          };

      fNOP.prototype = this.prototype;
      fBound.prototype = new fNOP();

      return fBound;
    };
  }
})();

垫片放在哪里?你会如何使用它? - Artjom B.
在PouchDB之前放入脚本标记。 - nlawson
1
或者在 Karma 中,您可以将其放入 files 列表中,然后再放入 pouchdb。 - nlawson
由于该项目已经通过bower安装了es5-shim,将其包含在karma中可以使其完美运行。我接受这个答案。 - vilsbole
这个解决了我使用RequireJS和PouchDB进行Jasmine/PhantomJS测试时遇到的类似问题。 - Mike Cavaliere

1

问题已经在PhantomJS 2+中得到解决。因此,更新Phantom node模块即可。

package.json中测试了以下测试相关模块的版本。

"karma": "0.13.21",
"karma-jasmine": "0.3.7",
"karma-phantomjs-launcher": "1.0.0",
"phantomjs-prebuilt": "2.1.3",

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接