【问题标题】:How can mocha know when event fired on a Controller $scope using $broadcast inside of a $promise?mocha 如何知道事件何时在 $promise 中使用 $broadcast 在控制器 $scope 上触发?
【发布时间】:2014-03-28 22:50:40
【问题描述】:

我找不到任何其他满足我需要的问题/答案,所以这里是:

在 AngularJS (1.2.14) 控制器中,我有一个事件侦听器,它在听到事件 ('fetchData') 时执行 ajax 调用以获取一些数据。获取成功后,将广播一个事件(称为“fetchSuccess”),一个指令正在侦听(尽管该部分无关紧要)。

$scope.$on('fetchData', function () {
            $scope
                .submitSearch()
                .then(function (results) {
                    $scope.$broadcast('fetchSuccess');
                }, function () {
                    $scope.$broadcast('fetchError');
                });
        });

所以,在我的测试中,我想做这样的事情(假设 'this.scope' 是测试套件中控制器上的一个新 $scope 对象):

it('should broadcast "fetchSuccess"', inject(function ($rootScope) {
        var scope = this.scope,
            spy = chai.spy(scope, '$broadcast');

        // trigger the $broadcast event that calls the fetch method
        scope.$broadcast('fetchData');

        $rootScope.$apply();

        expect(scope.$broadcast).to.be.called.with('fetchSuccess');
    }));

但我不清楚如何在断言中监听 $broadcast 事件。我不断收到此错误:AssertionError: expected function (name, args) {...}

明确一点,我的问题不在于事件广播器或运行时侦听器的功能;该应用程序按预期工作。问题在于监听测试套件中的事件。

请注意,上面的代码只是这个问题所需的必要sn-p。在我的应用程序中,还有其他变量/方法可以设置/调用,并且这些东西可以正确测试。这意味着如果我测试是否调用了实际的获取方法,或者是否正确设置了特定变量,这些测试就会通过。

我尝试混合和匹配范围变量,甚至通过scope.$on('fetchSuccess', fn) 收听$broadcast,但似乎没有任何效果。 fetchSuccess 事件似乎没有发出,或者我没有正确监听它。

提前致谢, 瑞恩。

【问题讨论】:

    标签: javascript angularjs unit-testing mocha.js chai


    【解决方案1】:

    所以,我找到了问题的答案,这都是我的错。虽然我确实不得不修改测试的编写方式,但核心问题就像监听错误事件一样简单!

    但是,对于那些想知道我的测试是什么样子的人,这里是最终测试(rootscope 在其他地方被设置为 $rootScope):

    it('should broadcast a "fetchSuccess" event', function (done) {
        var eventEmitted = false;
        this.scope.$on('fetchSuccess', function () {
                eventEmitted = true;
                done();
            });
    
            this.scope.$broadcast('fetchData');
    
        rootscope.$apply();
    
        eventEmitted.should.be.true;
    });
    

    没有必要监视 $broadcast 事件,AngularJS $on 监听器就足够了。

    【讨论】:

      猜你喜欢
      • 2015-12-08
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      • 2015-07-08
      相关资源
      最近更新 更多