【问题标题】:Get fixture data using sinon.fakeServer使用 sinon.fakeServer 获取夹具数据
【发布时间】:2012-06-05 18:10:07
【问题描述】:

我正在尝试使用 sinon.fakeServersinon.useFakeXMLHttpRequest 和 require.js 模拟 Backbone.Model.fetch 请求。

这是我无法正常工作的代码片段 (1)

我的问题是:
如何使用 sinon.fakeServer 获取夹具数据?
请在这段代码末尾的两个cmets。

附:
如果我发出 fetch 请求并评论有关 sinon.fakeServer 的代码,它会向服务器发出 get 请求。
如果我使用 sinon.fakeServer 发出 get 请求,它不会获取任何东西(服务器和夹具)


(1)

define([
    'js/models/myModel',
    'js/spec/fixtures/myModel.fixture'
], function (MyModel) {

            beforeEach(function () {

        this.myModel = new MyModel();

                console.log("fixtures", this.fixtures.Task, this);
                this.fixture = this.fixtures.Task.valid;
                this.fixtureTask = this.fixture.response;
                this.server = sinon.fakeServer.create();
                this.server.respondWith(
                    "GET",
                    Routing.generate("api_get_tasks"),
                    JSON.stringify(this.fixture)
                );
            });

            afterEach(function () {
                this.server.restore();
            });


            it("should make the correct request", function() {
                this.server.respond();

                this.feeds.fetch();

            console.log(this.fixture); // this response is OK
            console.log(this.myModel.attributes); // it does not take the value from this.fixture

            console.log("fixtures", this.fixtures.Task, this); // see the picture below

             });

});

【问题讨论】:

  • console.log("fixtures", this.fixtures.Task, this); 输出是什么?
  • @user1248256 我回复你,附上一张照片。

标签: javascript testing backbone.js jasmine sinon


【解决方案1】:

您不会在模型上调用fetch 方法。

试试这个:

 it("should make the correct request", function() {
        this.myModel.fetch();
        this.server.respond();
        console.log(this.fixture); // this response is OK
        console.log(this.myModel.attributes); // it does not take the value from this.fixture

        console.log("fixtures", this.fixtures.Task, this); // fixtures  Object  jasmine.Spec

 });

【讨论】:

  • 感谢您的回复。我做到了,但结果没有改变。无论如何,如果我尝试制作 this.myModel.fetch();那么结果就是模型定义中的defaults: {},而不是fixture
  • 嗯。您是否尝试过 successerror 回调到 fetch 方法调用以查看来自 sinon.fakeServer 的响应? this.myModel.fetch({success: function (m, resp) {console.log('success: %o, %o', m, resp)}, error: function (m, resp) {console.log('error: %o, %o', m, resp)}); 看来您应该使用this.fixtures.Task.valid.response 而不是this.fixtures.Task.valid 来响应,但我不确定。
  • @LorraineBernard 或者您可以展示 MyModel 原型?你实现了parse 函数吗?
  • Make this.myModel.fetch({success or error or complete...我没有任何结果。可能是因为我使用的是sinon.fakeServer。你知道另一种获取响应的方法吗?来自 sinon.fakeServer?谢谢
  • @LorraineBernard 显示示例:jsfiddle.net/SCZu9/2 fetch 回调在调用 sinon.fakeServer 响应时触发。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2019-04-29
  • 2019-11-11
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多