如何在茉莉测试框架中处理谷歌地图事件

How to handle google maps events in jasmine test framework

本文关键字:处理 谷歌地图 事件 框架 测试      更新时间:2023-09-26

我正在尝试使用jasmine框架为Google Maps编写Javascript测试。我要做的是初始化地图,改变边界(缩小),并测试地图是否正确缩小。

我遇到的问题是,jasmine似乎没有任何方法来处理事件。Jasmine有一个spyOn()方法,它查找方法的使用情况(而不是事件)。在jasmine中还有waits()方法,它等待特定的时间。这些方法都不适合处理事件。有人对茉莉花的事件有经验吗?

我正在使用的代码:

describe('Map view', function () {
    beforeEach(function () {
        $('body').append("<div data-role='page' id='page-map'><div id='map_canvas'></div></div>");
        this.view = new MapView({el: $('#map_canvas')});
    });
    afterEach(function () {
        $('body div#page-map').remove();
    });
    describe('zoom to a new bound in the map', function () {
        it('should set map bounds correctly', function () {
            this.view.zoomToBounds(this.fixtures.Locations.valid.bounds);
    
            google.maps.event.addListener(this.view.map, 'bounds_changed', function() {
                // expect() doesn't work in this context.. (ex: expect(5).toEqual(1) will pass)
                expect(this.getBounds().getSouthWest().lat()).toBeGreaterThan(self.fixtures.Locations.valid.bounds.minLat);
                expect(this.getBounds().getSouthWest().lng()).toBeGreaterThan(self.fixtures.Locations.valid.bounds.minLng);
                expect(this.getBounds().getNorthEast().lat()).toBeLessThan(self.fixtures.Locations.valid.bounds.maxLat);
                expect(this.getBounds().getNorthEast().lng()).toBeLessThan(self.fixtures.Locations.valid.bounds.maxLng);
            });
        });
    });
});

主干视图将启动,Google地图将呈现。zoomToBounds方法工作得很好,但当我想检查结果时,我遇到了一些问题。在google.maps.event.addListener()子句中,(茉莉花)expect()调用似乎不起作用。

最好的方法当然是使用jasmine方法直接捕获事件,但我还没有找到这样做的方法。

这里有人知道如何处理这个吗?

最好的方法当然是使用jasmine方法直接捕捉事件

你是否尝试过使用茉莉花间谍来监视对象的原型,该对象绑定了事件?我认为你的事件可能会在间谍设置之前绑定:

下面是一个简单的例子(在coffeescript中)

  it 'calls render when a model is added to the collection', ->
    spyOn(MyView.prototype, 'render')
    view = new MyView({
      collection : new Backbone.Collection([])
    })
    view.collection.add({})
    expect(view.render).toHaveBeenCalled()