0

我正在使用主干和茉莉花,现在尝试在保存模型时测试“同步”方法的 callCount。出于某种奇怪的原因,即使在 done 变量为真之后,同步处理程序也会继续处理同步(这是我计划停止测试) .

这是我的斑点:

describe('Model :: User', function() {

  var mockData = { name: 'Foo Bar' };

  beforeEach(function() {
    var that = this,
        done = false;

    require(['app/namespace','app/models/UserModel','app/collections/UsersCollection'], function(namespace, UserModel ,UsersCollection) {
        that.users = new UsersCollection();
        that.user = new UserModel();
         done = true;
    });

    waitsFor(function() {
      return done;
    }, "Create Models");




  });

  afterEach(function(){
    var done = false,
        isDone = function(){ return done; };

    this.users.fetch({
      success: function(c) {
        console.log('after the test calling destory of collection...')
        c.each(function(m){
          m.destroy();
        });
        done = true;
      }
    });

    waitsFor(isDone);

    done = false;
    this.user.destroy({
      success: function(){
        console.log('after the test calling destory of model...')
        done = true;
      }
    });

    waitsFor(isDone);

  });

  describe('.save()', function() {
    it('should call sync when saving', function() {
      var done = false,
          spy = jasmine.createSpy();
      this.user.on('sync', spy);
      this.user.on('sync', function(){

        console.log('checking spy.callCount-'+spy.callCount);
    //------------------------------------------------
        if(!done)//why i need this if ?!
            expect(spy.callCount).toEqual(1);
        done = true;

      }, this);

      this.user.save(mockData);


      waitsFor(function() { return done; });

    });

  });


});

只有当我在期望语句之前添加“if(!done)”条件时测试才能正常工作,否则它会继续计算测试后由破坏引起的同步调用......谢谢转发

4

1 回答 1

1

这个测试有一些问题。首先,您不需要sync在保存模型时测试该事件是否被触发,因为这是由另一个框架提供的,希望该框架经过测试。

其次,您应该使用SinonJs的假服务器,以免与异步调用混淆。使用 sinon 您的请求将立即被调用,这意味着您不需要. 回调中的断言似乎也有点奇怪。waitsFor

this.server = sinon.fakeServer.create();
server.respondWith({data: 'someData'})
server.autoRespond = true; //so when the request start the fake server will immediately call the success callback
var spy = jasmine.createSpy();
this.user.on('sync', spy);
this.user.save(mockData);
expect(spy.callCount).toEqual(1);
于 2013-05-09T13:28:08.267 回答