Backbone collection fetch not populating in Jasmine + Sinon spec

我是研究僧i 提交于 2019-12-11 07:26:53

问题


When I run this spec output I get "Expected 0 to equal 2." 2 is the correct length of model objects in my fixture so Sinon's fakeServer is responding properly with the mocked response. I can't figure out why my Collection has zero objects after fetch then. Any help would be really appreciated!

FYI: this is coming from following along the Backbone Sinon + Jasmine tutorial here: http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html

Spec:

describe "Todos collection", ->

  describe "when fetching models from the server", ->
    beforeEach ->
      @todo = sinon.stub(window, "Todo")
      @todos = new Todos()
      @fixture = @fixtures.Todos.valid
      @server = sinon.fakeServer.create()
      @server.respondWith "GET", "/todos", @validResponse(@fixture)

    afterEach ->
      @todo.restore()
      @server.restore()

    it "should parse todos from the response", ->
      @todos.fetch()
      @server.respond()
      expect(@todos.length).toEqual @fixture.response.todos.length

Model:

class window.Todos extends Backbone.Collection
  model: window.Todo
  url: "/todos"
  comparator: (todo) ->
    todo.get('priority')
  parse: (res) ->
    res.response.todos

EDIT:

Buck Doyle below has helped me see there is no spec problem. I have some kind of issue with my Jasmine Headless Webkit config, and if the specs are run with Jasmine standalone they pass.


回答1:


Theory: you need to wait for the “server” to respond to the request before checking for the result. Mocking the response isn’t enough: the fetch is still asynchronous.

Try a waits or a more complicated-but-elegant waitsFor as described at https://github.com/pivotal/jasmine/wiki/Asynchronous-specs



来源:https://stackoverflow.com/questions/10509708/backbone-collection-fetch-not-populating-in-jasmine-sinon-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!