如何从 AMD 模块中的方法 return json?

how to return json from method inside an AMD module?

在尝试测试我的 json object 时,我一直收到 "undefined"。我不明白为什么?

修订: 我已经阅读...深入阅读...此处列出的 post...How do I return the response from an asynchronous call?

在那个最史诗般的答案的末尾 post,作者提到根本不使用 $.getJSON。在我的情况下,我不认为这是一个选择。我的情况有所不同,因为我需要使用 $.getJSON 才能获得 json。此外,我的配置不同之处在于我的 $.getJSON 调用是在 AMD 模块内的原型方法内。那篇文章确实帮助我理解了我可以 return 整个 $.getJSON 回来,我已经更新了我的代码以反映这一点。所以现在...

当我从我的测试文件中调用 codelib.gotjson 并测试结果 Object 中某些内容的值时,我需要做什么?

注意:我可以在 chrome 控制台的 "Object" 内部看到 console.dir(result) 让我看到。在那个 object 里面我可以看到一个 "responseText" 包含我想要的珍贵的 json 字符串。但是我现在卡在如何为它写断言了?

我想写类似....

assert.equal(Object.responseText.name,"bob","is equal to bob")

我现在很接近了。任何帮助表示赞赏。谢谢。

codelib.js

"use strict";

define(function() {
  //constructor
  function Codelib(a,b){
    // if u had passed vars
    this.b = b;
    this.a = a;
  }

  //methods
  Codelib.prototype.code = function(a, b) {
    return (a + b);
  };

  //methods
  Codelib.prototype.gotjson = function() {
      return $.getJSON("https://api.twitch.tv/kraken/streams/MedryBW")
          .done(function (data) {
            console.log('gotJSON: ');
            console.dir(data);
          })
          .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
          });
  };


  return Codelib;
});

测试文件codeTest.js

"use strict";
define(['src/codelib','jquery'], function(Codelib){
  var run = function(){
    QUnit.test('code should return the sum of the two supplied numbers.',function(assert){
      var codelib = new Codelib();
      assert.equal(codelib.code(1,1),2, 'The return should be 2.');
      assert.equal(codelib.code(-2,1),-1, 'The return should be -1.');
    });

    QUnit.test("As a user, I can see whether MedryBW is currently streaming on Twitch.tv",function(assert){
    var codelib = new Codelib();
    var result = codelib.gotjson();
    console.log('in test: ');
    console.dir(result);

      assert.equal(codelib.gotjson(),1, 'should be true');
    });

  };
  return {run: run}
});

注意:结果 Object 在 chrome 控制台中找到:

Object:
...
responseText: "{"_links":    {"self":"https://api.twitch.tv/kraken/streams/medrybw"...etc
...

In that post towards the end of that most epic answer, the author mentions to simply not use $.getJSON.

我认为您误解了那部分答案。如果您希望 Ajax 请求同步,则不能使用 $.getJSON。但是,您不应该希望请求是同步的。我的意思是,该部分标题为 "Not recommended: Synchronous "AJAX“调用”,我的意思是 不推荐 当我说的时候:)


您应该使用回调或承诺来处理响应,如答案前面所述。那里说你应该 returning $.getJSON 的 return 值(承诺/延迟 object):

Codelib.prototype.gotjson = function() {
  return $.getJSON("https://api.twitch.tv/kraken/streams/MedryBW");
};

并让调用代码注册回调:

codelib.gotjson().done(function(result) {
  assert.equal(result, 1, 'should be true');
});

但是,QUnit 期望测试是同步的,因此它不会等到收到 Ajax 响应。幸运的是,QUnit supports async tests 还有:

var done = assert.async();
codelib.gotjson().done(function(result) {
  assert.equal(result, 1, 'should be true');
  done();
});