2012-11-28 86 views
1
describe('Ajax', function() { 
    beforeEach(function() { 
    // Instantiate module and reference it with this.testUser 
    this.testUser = new TestUser(); 
    // Reference sinon.spy with this.spySetToken 
    this.spySetToken = sinon.spy(this.testUser, 'setToken'); 
    }); 
    afterEach(function() { 
    this.spySetToken.restore(); 
    }); 
    it('Does it respond with that data', function() { 
    // Wrap $.ajax method and invoke success callback from ajax passing it a 'string'. 
    sinon.stub($, 'ajax').yieldsTo('success', 'Custom response string'); 
    // test to see if my method that's inside the success callback is called with the string 
    expect(this.spySetToken.toHaveBeenCalledWith('Custom response string'); 
    }); 

}); 

我得到'期望函數被稱爲'。測試阿賈克斯茉莉花sinon

如何成功測試Ajax成功方法?

+0

那麼你的測試似乎沒有做任何Ajax調用(你只是設置間諜)。你確定你不缺少代碼嗎? – HoLyVieR

回答

1

那麼我會使用sinon.fakeServer之前,但我沒有意識到,它觸發原始ajax調用的成功。

因此,解決辦法是要做到這一點:

beforeEach(function() { 
    var server = sinon.fakeServer.create(); 
    this.server.respondWith(
    "GET", 
    "/the/url" // This should marry up to the url being tested i believe 
    [200, {"Content-Type":"application/json"}, 
    '{response:"json"}'] 
); 
}; 

it('should set my model', function() { 
    this.server.respond(); 
    expect(myModel.get('property').toEqual('); 
} 

Sinon.server將觸發Ajax調用成功的功能,讓你可以測試你可能有成功的方法的任何功能。