Testing routers in backbone.js properly?(正确测试backbone.js中的路由器?)
问题描述
所以我刚刚开始使用 sinon.js
& 为我正在进行的 javascript 应用程序编写测试.jasmine.js
.总体上运行良好,但我还需要能够测试我的路由器.
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.
路由器在其当前状态下将触发许多视图和其他内容,通过调用依赖于应用程序的 Backbone.navigate
来终止当前的 jasmine.js
测试状态和 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.
那么我怎样才能测试到不同位置的路由是否可行,同时保持路由器沙盒"并且不允许它们更改路由?
So how could I test that routing to different locations would work, while keeping the routers "sandboxed" and not allowing them to change route?
我可以设置某种模拟函数来监控 pushState 变化或类似情况吗?
Can I set up some sort of mock function that will monitor pushState changes or similar?
推荐答案
这是我最终使用自己的.我通过扩展它并用空白方法覆盖方法来制作路由器的模拟版本,以防止它在被调用时调用任何进一步的逻辑:
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();
});
});
请注意,上面使用 sinon.js
来创建 spy,与 underscore.js
一起提供 size
功能.
Note that sinon.js
is used above to create the spy, along with underscore.js
to provide the size
function.
这篇关于正确测试backbone.js中的路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:正确测试backbone.js中的路由器?
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01