小编And*_*rea的帖子

Jasmine + AngularJS:如何测试$ rootScope.使用参数调用$ broadcast?

我正在尝试编写一个单元测试来验证$rootScope.$broadcast('myApiPlay', { action : 'play' });被调用.

这是myapi.js

angular.module('myApp').factory('MyApi', function ($rootScope) {
    var api = {};
    api.play = function() {
        $rootScope.$broadcast('myApiPlay', { action : 'play' });
    }
    return api;
});
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试:

describe('Service: MyApi', function () {

    // load the service's module
    beforeEach(module('myApp'));

    // instantiate service
    var MyApi;
    var rootScope;

    beforeEach(function () {
        inject(function ($rootScope, _MyApi_) {
            MyApi = _MyApi_;
            rootScope = $rootScope.$new();
        })
    });
    it('should broadcast to play', function () {
        spyOn(rootScope, '$broadcast').andCallThrough();
        rootScope.$on('myApiPlay', function (event, data) {
            expect(data.action).toBe('play'); …
Run Code Online (Sandbox Code Playgroud)

javascript jasmine angularjs karma-jasmine yeoman-generator-angular

8
推荐指数
1
解决办法
2万
查看次数