使用mocha.js测试jQyery.get不起作用,其他延迟(RSVP)也不起作用

时间:2015-09-17 08:16:03

标签: javascript jquery node.js promise mocha

我试图使用mocha.js运行一些JavaScript测试。到目前为止,一切都运行良好,但我在测试任何有关jQuery请求或其他承诺/推迟的问题时遇到了很大的问题。

我的代码在浏览器中运行得非常好,以前大量使用$.Deferred但是使用Mocha我无法运行它。

我尝试了不同的写作方法,并转而使用了#34;正确的"承诺库,因为显然jQuery会给它的实现带来麻烦。

正确的RSVP.Promises工作正常,RSVP.Defer仍然没有,我无法获得任何涉及jQuery的工作(如发出请求)。

我确实找到了一些建议,将jQuery包装到正确的Promise中应该可以完成这项工作,但是找不到任何真正这样做但不会失败的方法。

以下是展示问题的测试用例:

'use strict';

var RSVP = require('rsvp');
var    $ = require('jquery');

describe('promises', function() {

  it('works with RSVP.Promise', function(done) {
    new RSVP.Promise(function(resolve, reject) {
      resolve();
    }).then(function() {
      done();
    });
  });

  it('works with RSVP.Deferred promise', function(done) {
    RSVP.defer().done(function() {
      done();
    }).resolve();
  });

  it('works with $.Deferred', function(done) {
    $.Deferred().done(function() {
      done();
    }).resolve();
  });

  it('works with $.get (promise syntax)', function(done) {
    $.get('http://google.com', function() {
      done();
    });
  });

  it('works with $.get (defered syntax)', function(done) {
    $.get('http://google.com').done(function() {
      done();
    });
  });

});

以:

运行

$ mocha --compilers jsx:babel/register

给我以下输出:

promises
    ✓ works with RSVP.Promise
    1) works with RSVP.Deferred promise
    2) works with $.Deferred
    3) works with $.get (promise syntax)
    4) works with $.get (defered syntax)


  1 passing (59ms)
  4 failing

  1) promises works with RSVP.Deferred promise:
     TypeError: undefined is not a function
      at Context.<anonymous> (test/test.js:17:26)

  2) promises works with $.Deferred:
     TypeError: undefined is not a function
      at Context.<anonymous> (test/test.js:23:21)

  3) promises works with $.get (promise syntax):
     TypeError: undefined is not a function
      at Context.<anonymous> (test/test.js:31:7)

  4) promises works with $.get (defered syntax):
     TypeError: undefined is not a function
      at Context.<anonymous> (test/test.js:37:7)

只要没有涉及jQuery Promise / Defer,其他测试运行完全正常。

是否有更好的解决方案,而不是放弃jQuery来提出请求,还是我做了一般错误的事情?测试的目的是测试实际的请求/响应,因此这里也没有选择模拟请求。

就像我说的那样,代码在浏览器中运行得非常好,无论是否使用Promise / Defer jQuery。所以我猜测它是跑步者或运行的node.js环境(?)的问题。

1 个答案:

答案 0 :(得分:1)

要测试HTTP请求,您可以使用:https://github.com/visionmedia/supertest

这很棒,或者不是使用jQuery来发出你可以使用的HTTP请求:https://github.com/visionmedia/superagent

我认为它在nodeJS中比使用jQuery更标准。