問題描述
所以我剛剛開始使用 sinon.js
& 為我正在進(jìn)行的 javascript 應(yīng)用程序編寫測(cè)試.jasmine.js
.總體上運(yùn)行良好,但我還需要能夠測(cè)試我的路由器.
So I've just started to write tests for my in-progress javascript app, using sinon.js
& jasmine.js
. Works pretty well overall, but I need to also be able to test my routers.
路由器在其當(dāng)前狀態(tài)下將觸發(fā)許多視圖和其他內(nèi)容,通過調(diào)用依賴于應(yīng)用程序的 Backbone.navigate
來終止當(dāng)前的 jasmine.js
測(cè)試狀態(tài)和 UI 迭代.
The routers, in their current state, will trigger an number of views and other stuff, terminating the current jasmine.js
test by invoking Backbone.navigate
dependent on application state and UI itneraction.
那么我怎樣才能測(cè)試到不同位置的路由是否可行,同時(shí)保持路由器沙盒"并且不允許它們更改路由?
So how could I test that routing to different locations would work, while keeping the routers "sandboxed" and not allowing them to change route?
我可以設(shè)置某種模擬函數(shù)來監(jiān)控 pushState 變化或類似情況嗎?
Can I set up some sort of mock function that will monitor pushState changes or similar?
推薦答案
這是我最終使用自己的.我通過擴(kuò)展它并用空白方法覆蓋方法來制作路由器的模擬版本,以防止它在被調(diào)用時(shí)調(diào)用任何進(jìn)一步的邏輯:
Here's what I ended up using myself. I made a mock version of the router by extending it and overriding the methods with a blank method to prevent it from invoking any further logic when being called:
describe("routers/main", function() {
beforeEach(function() {
// Create a mock version of our router by extending it and only overriding
// the methods
var mockRouter = App.Routers["Main"].extend({
index: function() {},
login: function() {},
logoff: function() {}
});
// Set up a spy and invoke the router
this.routeSpy = sinon.spy();
this.router = new mockRouter;
// Prevent history.start from throwing error
try {
Backbone.history.start({silent:true, pushState:true});
} catch(e) {
}
// Reset URL
this.router.navigate("tests/SpecRunner.html");
});
afterEach(function(){
// Reset URL
this.router.navigate("tests/SpecRunner.html");
});
it('Has the right amount of routes', function() {
expect(_.size(this.router.routes)).toEqual(4);
});
it('/ -route exists and points to the right method', function () {
expect(this.router.routes['']).toEqual('index');
});
it("Can navigate to /", function() {
this.router.bind("route:index", this.routeSpy);
this.router.navigate("", true);
expect(this.routeSpy.calledOnce).toBeTruthy();
expect(this.routeSpy.calledWith()).toBeTruthy();
});
});
請(qǐng)注意,上面使用 sinon.js
來創(chuàng)建 spy,與 underscore.js
一起提供 size
功能.
Note that sinon.js
is used above to create the spy, along with underscore.js
to provide the size
function.
這篇關(guān)于正確測(cè)試backbone.js中的路由器?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!