【问题标题】:Backbone Models not updating after Sinon.fakeServer responds to model.fetchSinon.fakeServer 响应 model.fetch 后骨干模型未更新
【发布时间】:2018-06-18 18:18:23
【问题描述】:

我正在尝试为我们的 Backbone 应用程序编写一个测试套件。我们使用 Jest 作为测试框架,使用 Sinon 进行服务器模拟。

一个示例测试看起来像

device.test.js

describe('API integration', ()=>{
        let response = {"data": {
                "attributes": {
                    "created_at": "2018-06-14T07:05:14.919Z",
                },
                "id": "234",
                "type": "device"
         }};

        let server = sinon.fakeServer.create();
        afterAll(() => {
            server.restore();
        });

        let device = new Device({
            id: '234'
            created_at: null,
            agent_code: null,
            device_code: null,
        });

        server.respondWith('GET',
            'api/device/234',
            [200, {"Content-Type": "application/json"},
            JSON.stringify(response)]);

        device.fetch();
        server.respond();
        it('fetches to the right URL', ()=>{
            // these both pass
            expect(server.requests[0].method === 'GET');
            expect(server.requests[0].url === 'api/device/234');
        });
        it('updates its fields properly after a fetch', ()=>{
           // this test fails
           expect(device.get('created_at')).toBe(response.attributes.created_at);

        });           
    });

我使用this article 作为示例,说明如何使用 sinon 测试骨干模型(滚动到几乎底部以使用 fakeserver)以及使用sinon fakeserver docs

根据我的阅读,server.respond() 应该评估所有异步请求,因此模型应该同步更新。也就是说,我的期望是在server.respond 之后对device 的任何引用都应该是指一个获取后的device 模型。我的期望没有得到满足 - 在致电 server.respond() 后,device.get('created_at') 仍然是 undefined。当我们的应用程序正在运行时,生产中的情况并非如此。

以防万一,我尝试将测试放入 {success: function(){}} 回调,以及 .then.done,但随后测试无法运行,console.log() 或任何其他调试工作也无法运行.

如何使用 Sinon.fakeServer 在 Jest 中测试 Backbone.model.fetch() 等异步方法?

编辑:This answer 让我想知道是否可能甚至调用了 parse - 也许我正在异常地构造我的返回数据。 Parse 确实被调用了,所以现在我怀疑这不是异步问题,而是我如何在response 对象中构造我的数据。

【问题讨论】:

    标签: javascript asynchronous jestjs sinon synchronous


    【解决方案1】:

    答案是我的模型的id 属性与我的API_MOCKS 帮助文件中响应对象的id 属性不匹配。它与异步无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多