javascript - 使用 sinon.fakeServer 获取夹具数据

标签 javascript testing backbone.js jasmine sinon

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

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

我的问题是:
如何使用 sinon.fakeServer 获取 fixture 数据?
请在这段代码末尾添加两条注释。

附言:
如果我在 fetch 请求中注释了关于 sinon.fakeServer 的代码,它就会向服务器发出 get 请求。
如果我使用 sinon.fakeServer 发出获取请求,它不会获取任何东西(服务器和夹具)


(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

             });

});

enter image description here

最佳答案

您没有在模型上调用 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

 });

关于javascript - 使用 sinon.fakeServer 获取夹具数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10834392/

相关文章:

javascript - Angularjs uri组件是如何编码的

c# - .net 是否根据测试方法创建实例?

backbone.js - 使用 Jasmine 测试时 Backbone Collection 为空

javascript - Hammer JS 不适用于主干

javascript - 为 ajax 使用多个方法 token 有什么好处?

javascript - Jquery/Javascript 循环 div 滚动条

javascript - jQuery 一起从多个选择中获取值

javascript - 如何避免为每个 Jest 测试用例重新运行异步 API 调用?

javascript - 验证在自动回发时消失

java - 开关 : 7 of 19 missed 的 eclemma 分支覆盖率