标签: angular-mock

如何模拟在提供程序私有函数中手动注入的$ window?

我有以下提供者:

angular.module('MyApp').provider('MyDevice', function () {

    var ngInjector = angular.injector(['ng']),
        $window = ngInjector.get('$window');

    function isMobileDevice () {
        return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/)
            .test($window.navigator.userAgent || $window.navigator.vendor || $window.opera);
    }

    this.$get = function () {
        return {
            isDesktop: function () {
                return !isMobileDevice();
            },
            isMobile: function () {
                return isMobileDevice();  
            }
        };
    };

});
Run Code Online (Sandbox Code Playgroud)

以下测试规范:

describe('MyDeviceProvider', function () {

    var myDevice;

    beforeEach(function () {
        inject(['MyDevice', function (_myDevice_) {
            myDevice = _myDevice_;
        }]);
    });

    it('Test #1', function () {
        // Mock '$window.navigator.userAgent' to "desktop"
        expect(myDevice.isDesktop()).toEqual(true);
        expect(myDevice.isMobile()).toEqual(false); …
Run Code Online (Sandbox Code Playgroud)

unit-testing angularjs karma-jasmine angular-mock

4
推荐指数
1
解决办法
8431
查看次数

在Jasmine/Karma中测试$ interval

我有一个简单的工厂

angular.module('myApp.dice',[]).factory('Dice', ['$interval', function($interval){
    return {
      rollDice: function(){
        return $interval(function(c){
               count++;
          }, 100, 18, false, 0);
      }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

在我的测试案例中,我有

describe('rolling dice', function(){
      var promise, promiseCalled = false, notify = false;
      beforeEach(inject(function(){
        promise = Dice.rollDice();
        promise.then(function(){
          promiseCalled = true;
        });

      }));

      it('should invoke a promise', inject(function(){
        expect(promise).toBeDefined();
      }));

      it('should set promiseCalled', inject(function($rootScope, $interval){


        expect(promiseCalled).toEqual(true);
      }));
    });
Run Code Online (Sandbox Code Playgroud)

如何触发间隔或解决承诺?让测试成真?

jasmine angularjs karma-runner karma-jasmine angular-mock

4
推荐指数
1
解决办法
2638
查看次数

使用Jest对Angular Directives进行单元测试

在这个极其简化的角度指令单元测试中,我觉得我缺少一些关键的东西:

import * as angular from 'angular'
import 'angular-mocks'

const app = angular.module('my-app', [])

app.directive('myDirective', () => ({
    template: 'this does not work either',
    link: (scope, element) => { // have also tried compile fn
        console.log('This does not log')
        element.html('Hi!')
    }
}))

describe('myDirective', () => {
    var element, scope

    beforeEach(app)

    beforeEach(inject(($rootScope, $compile) => {
        scope = $rootScope.$new()
        element = $compile('<my-directive />')(scope)
        scope.$digest()
    }))

    it('should actually do something', () => {
        expect(element.html()).toEqual('Hi!')
    })
})
Run Code Online (Sandbox Code Playgroud)

当jest运行时,看起来该指令尚未链接/编译/无论如何

 FAIL  test/HtmlToPlaintextDirective.spec.js
  ? myDirective › should …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-mock jestjs

4
推荐指数
1
解决办法
4080
查看次数

AngularJS - 间隔不会被刷新

我有角度服务功能,我愿意测试:

doSomeTask: function (ids, callback) {
  $http.put('/get_job', {'ids': ids}).success(function (data) {
    var statusCheck = $interval(function() {
      $http.get('check_status?=' + data.job_id).success(function (data) {
        if(data.completed) {
          $interval.cancel(statusCheck);
          // and do something...
        }
      });
    }, 2000);
  });
Run Code Online (Sandbox Code Playgroud)

以下测试:

describe('MyService', function() {

  var myService;
  var $httpBackend;
  var $interval;

  beforeEach(module('myModule'));

  beforeEach(inject(function(_$httpBackend_, _$interval_, $rootScope, MyService) {
    $httpBackend = _$httpBackend_;
    $interval = _$interval_;
    myService  = MyService;
  }));

  describe('doSomeTask', function () {
    beforeEach(function () {
      $httpBackend.expectPUT("/get_job").respond({ job_id: '123' });
      $httpBackend.expectGET("/status_check").respond({ completed: true });
    });

    it('should do it well', inject(function …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angular-mock

3
推荐指数
1
解决办法
2247
查看次数

Jasmine - 测试控制器是否存在错误

我有一个简单的控制器:

app.controller("RegisterController", function ($scope, $location) {

    // Do something

});
Run Code Online (Sandbox Code Playgroud)

而我所要做的就是测试这个控制器的定义:

describe('RegisterController', function() {

    var $rootScope, $scope, $controller;

    beforeEach(module('myApp'));

    beforeEach(inject(function(_$rootScope_, _$controller_){
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $controller = _$controller_;

        $controller('RegisterController', {'$rootScope' : $rootScope, '$scope': $scope});
    }));

    it('should exist', function() {
        expect($controller).toBeDefined();
    });
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

jasmine angularjs karma-jasmine angular-mock

3
推荐指数
1
解决办法
5125
查看次数

使用inject函数不能使用beforeEach

这是来自karma.conf.js文件:

module.exports = function (config) {
  config.set({
      frameworks: ['mocha', 'chai'],
      files: [
        'bower_components/angular/angular.js',
        'bower_components/angular-mocks/angular-mocks.js',
        'public/ng-app/module.js',
        'public/ng-app/**/*.js',
        'test/ng/**/*.spec.js'
      ],
  ...
Run Code Online (Sandbox Code Playgroud)

我试图使用beforeEach函数注入这样:

describe('my.test', function () {
  beforeEach(module('app'));

  var MyService;
  beforeEach(inject(function (_MyService_) {
    MyService = _MyService_;
  }));

  describe('#send', function () {
    it('exists', function () {
      expect(MyService.save).to.exist;
    });
  });

});
Run Code Online (Sandbox Code Playgroud)

但是beforeEach(inject(function(...)...);当我尝试运行测试时,部分代码会导致此错误:

PhantomJS 1.9.8 (Windows 8 0.0.0) my.test "before each" hook: workFn for "exists" FAILED
        Error: [$injector:modulerr] Failed to instantiate module ng due to:
        TypeError: 'undefined' is not an object (evaluating 'Function.prototype.bind.apply')
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚问题是什么.有人有什么想法吗?谢谢.

angularjs angular-mock karma-mocha

3
推荐指数
1
解决办法
2120
查看次数

在angular 4项目中模拟功能性e2e量角器测试中的其余调用

我们有一个庞大的项目,我们编写了许多测试用例,以涵盖e2e功能测试用例中的许多实际场景用户行为。

随着测试的进行,它会进行大量的调用以完成测试用例。当我们在酱料实验室中使用其他浏览器时,它会倍增5-9倍。

我要模拟所有其余的调用,这样就不会对实际服务器进行任何真正的调用,但是会在内部对其进行处理。它用于功能e2e测试,而不是单元测试,因为我们使用jasmine模拟了所有单元测试spyOn

我已经探索json-server$httpBackend量角器。子服务器不合适,因为它不能很好地处理应用程序的发布,放置,删除呼叫。如果是$ httpBackend

我已经看完了这篇文章,它涉及的是andularJs应用程序而不是angular应用程序,也涉及到有关angularJs的单个rest调用模拟,而不是所有rest调用。

为angularjs看了这个angularjs 多重模拟,也为angularjs 看到了它,而不是angularjs,看起来像这样更改了查询参数的原始REST URL。

protractor angular-mock angular angular-e2e angular-test

3
推荐指数
1
解决办法
6425
查看次数

在简单的Jasmine测试中注入$ log服务

是的,我是Angular和Jasmine的新手,我无法弄清楚如何为我的测试注入一个模拟$ log.这是测试:

(function () {
    'use strict';

    describe('basic test', function(){
        it('should just work', function(){
            var $log;

            beforeEach(inject(function(_$log_){
                $log = _$log_;
            }));

            $log.info('it worked!');
            expect($log.info.logs).toContain(['it worked!']);
        });
    });

}())
Run Code Online (Sandbox Code Playgroud)

这在注入行上失败并出现错误:

TypeError: Cannot set property 'typeName' of undefined
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

jasmine angularjs angular-mock

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

角度资源承诺捕获,茉莉花toThrow()

我在角度控制器中有一些代码:

user是一个angular $资源,在调用get方法时返回一个promise.

$scope.credentials = {
        username:"",
        password:"",
        rememberMe:false
    };

var currentUser  = {};

$scope.login = function(callback){
        user.get($scope.credentials)
            .$promise
            .then(function(user){
                $scope.currentUser = user;
                return cb ? cb(user) : user;
            })
            .catch(function(res){
                throw "LoginError";
            });

};
Run Code Online (Sandbox Code Playgroud)

我正试图测试它是否抛出错误与茉莉如此:

expect(function(){
  scope.login();
}).toThrow();
Run Code Online (Sandbox Code Playgroud)

但是抛出了这个错误:

抛出异常的预期函数.

我已经测试了承诺的接受度,它按预期工作,但我假设有一些我无法处理的异步方面.

我也试过调用传入并调用done(),但这也不起作用.

编辑:

我这样嘲笑我的后端:

beforeEach(inject(function($rootScope,$controller,_$httpBackend_){



            $httpBackend = _$httpBackend_;
            successCallback = jasmine.createSpy();
            errorCallback = jasmine.createSpy();


            scope = $rootScope.$new();
            controller = $controller('LoginController',{
                '$scope':scope
            });

        }));

afterEach(function(){
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
Run Code Online (Sandbox Code Playgroud)

请注意,我的其他测试确实有效,我尝试了其他场景,其中服务器返回200和用户,一切正常.我专门测试$ scope.login()在收到服务器错误时是否抛出错误.

javascript jasmine angularjs karma-jasmine angular-mock

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

错误:[$ injector:unpr]未知提供者:$$ rAFProvider

使用Karma测试Angular获取错误:

    Error: [$injector:modulerr] Failed to instantiate module ngMock due to:
    Error: [$injector:unpr] Unknown provider: $$rAFProvider
Run Code Online (Sandbox Code Playgroud)

Angular mock,Angular版本错误?我听过详细说明角度模拟版本或角度版本更改的解决方案 - 这似乎是一个坏主意,因为我想测试与应用程序开始时相同的版本.其他人有这样的错误吗?

angularjs karma-runner angular-mock

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

单元测试 $mdDialog 角材质

我在函数内调用了一个 $mdDialog 。我想对 $mdDialog 进行单元测试并取消案例。

下面是我的控制器代码(app.controller.js)。

 (function () {
    'use strict';

    app.controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['$scope', '$mdDialog'];

    function AppCtrl($scope, $mdDialog) {

        $scope.saveEntry = function (ev) {
            var confirm = $mdDialog.prompt()
                .title('Save Entry')
                .textContent('If you want, you can add a description to explain what you changed.')
                .placeholder('Version Description')
                .ariaLabel('Version Description')
                .initialValue('')
                .targetEvent(ev)
                .ok('Save')
                .cancel('Cancel');

            $mdDialog.show(confirm).then(function (result) {
                $scope.status = true;
            }, function () {
                $scope.status = false;
            });
        };
    }

})();
Run Code Online (Sandbox Code Playgroud)

以下是规范代码(app.controller.spec.js):

describe('Unit test AppController: mdDialog', function …
Run Code Online (Sandbox Code Playgroud)

unit-testing angularjs karma-jasmine angular-mock angular-material

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

与茉莉花一起使用上下文

我想使用茉莉花的上下文,所以我可以组织我的模拟返回.这是一些伪代码来演示我想要做的事情.我希望这两个期望都能通过:

describe('a module', function(){
    var whatTheFunctionReturns;
    beforeEach(function(){
        module('anApp', function($provide){
            $provide.value('aFactory', { aFunction: whatTheFunctionReturns })
        }
    });

    describe('when the function returns alpha', function(){
        whatTheFunctionReturns = 'alpha'

        it('should get data from a service', function(){
            expect(aFactory.aFunction).toEqual( 'alpha' )
        }); 
    });
    describe('when the function returns beta', function(){
        whatTheFunctionReturns = 'beta'

        it('should get data from a service', function(){
            expect(aFactory.aFunction).toEqual( 'beta' )
        }); 
    });
});
Run Code Online (Sandbox Code Playgroud)

请仔细阅读以上内容.你看到我想做什么了吗?代码

$provide.value('aFactory', { aFunction: whatTheFunctionReturns })
Run Code Online (Sandbox Code Playgroud)

在beforeEach块中写入一次,但变量

whatTheFunctionReturns
Run Code Online (Sandbox Code Playgroud)

在两个描述的块中更改,when the function returns alpha并且when the function returns beta. …

jasmine angularjs angular-mock

1
推荐指数
1
解决办法
2035
查看次数

角度测试失败"minErr"

我无法弄清楚这个测试我做错了什么.这是我对该项目的第一次测试.

describe('Controller: landingCtrl', function () {
  var scope;

  beforeEach(angular.mock.module('myWebApp'));

  beforeEach(angular.mock.inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    scope.filters = {
      date: 'This Week'
    };

    $controller('landingCtrl', {
      $scope: scope
    });
  }));

  it('dateFilter should return true', function () {
    expect(true).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

这是输出:

Firefox 34.0.0 (Windows) Controller: landingCtrl dateFilter should return true FAILED
    minErr/<@app/bower_components/angular/angular.js:63:12
    loadModules/<@Capp/bower_components/angular/angular.js:4138:15
    forEach@app/bower_components/angular/angular.js:323:11
    loadModules@app/bower_components/angular/angular.js:4099:5
    createInjector@app/bower_components/angular/angular.js:4025:11
    workFn@app/bower_components/angular-mocks/angular-mocks.js:2425:44
Run Code Online (Sandbox Code Playgroud)

testing angularjs karma-jasmine angular-mock

1
推荐指数
1
解决办法
732
查看次数