标签: angular-mock

使用Angular mock为Backendless开发加载JSON文件

我在单独的.js文件中为前端后端环境编写了这个小代码.myfile.json每当有一个ajax调用时我都需要得到/somelink.

angular.module('myApp')
.config(function($provide) {
  $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
})
.run(function($httpBackend, $http) {

  $httpBackend.whenGET('/somelink').respond(function(method, url, data) {
    $http({method: 'GET', url: '/somelink/myfile.json'})
    .success(function(data, status, headers, config) {
      return data;
    })
    .error(function(data, status, headers, config) {
    });

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

但是这段代码不起作用并且给了我错误:

Error: Unexpected request: GET /somelink/myfile.json
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

请注意,我不想直接调用$ http来获取代码中的.json文件,因为这会丢弃生产代码.这样做的目的是将此代码分别保留在后端开发中.

谢谢.

更新1:

我补充说:

$rootScope.$apply(); 
$httpBackend.flush();
Run Code Online (Sandbox Code Playgroud)

现在我还有另外一个错误: Uncaught Error: No pending request to flush !

更新2:

玩完之后,我发现了一个小黑客.我把它放在.run()所有其他$ httpBackend模拟之前.此.js文件也必须放在所有控制器/服务/指令之前和app.js引导程序之后.

  var data;

  $.ajax({
    type: 'GET',
    async: false,
    url: '/somelink/myfile.json'
  }).success(function(res) {
    data …
Run Code Online (Sandbox Code Playgroud)

javascript ajax json angularjs angular-mock

9
推荐指数
2
解决办法
8039
查看次数

为什么针对angular-google-maps提供程序的此测试失败?

我正在尝试测试使用的模块angular-google-maps.它失败了,因为angular.mock.inject找不到uiGmapGoogleMapApiProvider:

Error: [$injector:unpr] Unknown provider: uiGmapGoogleMapApiProviderProvider <- uiGmapGoogleMapApiProvider
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚出了什么问题.这是简化的测试用例:

'use strict';

describe('this spec', function() {
    beforeEach(module('uiGmapgoogle-maps'));

    it('tries to configure uiGmapGoogleMapApiProvider', inject(function(uiGmapGoogleMapApiProvider) {
        expect(uiGmapGoogleMapApiProvider.configure).toBeDefined();
    }));
});
Run Code Online (Sandbox Code Playgroud)

整个过程可以作为GitHub中可立即运行的Angular项目提供.如果您发现问题,请在此处回答Stack Overflow.如果您还向GitHub存储库提交拉取请求,则可获得奖励积分.

javascript angularjs karma-runner angular-mock angular-providers

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

如何测试Angular模块的配置功能?

我在configAngular 的函数中定义了一些module我想要进行单元测试的设置代码.我不清楚我应该怎么做.下面是一个简化的测试用例,展示了我是如何陷入困境的:

'use strict';

angular.module('myModule', []).config(['$http', '$log', function($http, $log) {
    $http.get('/api/getkey').then(function success(response) {
        $log.log(response.data);
    });
}]);

describe('myModule', function() {
    it('logs a key obtained from XHR', inject(function($httpBackend) {
        $httpBackend.expectGET('/api/getkey').respond(200, '12345');
        angular.module('myModule');
        $httpBackend.flush();
    }));
});
Run Code Online (Sandbox Code Playgroud)

这显然不是正确的方法,因为我收到以下错误:

Error: No pending request to flush !
Run Code Online (Sandbox Code Playgroud)

与上面的测试代码完整的,现成的运行角度的项目可以发现在GitHub上.如果您知道如何处理此场景,请在此处回答Stack Overflow.如果您还向GitHub仓库提交拉取请求,则可获得奖励积分.

javascript angularjs karma-runner karma-jasmine angular-mock

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

TypeError:angular.element.cleanData不是函数

在尝试使用时,我的业力单元测试中出现以下错误 inject()

  Example
    ? should wait for promise to resolve and have a result
    Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

  ? "after each" hook for "should wait for promise to resolve and have a result"
    TypeError: angular.element.cleanData is not a function
        at Function.module.$$cleanup (base/app/bower_components/angular-mocks/angular-mocks.js?aa216eb2339283c5ab5aa192023171aa202a2bbd:2776:23)
        at Context.module.$$afterEach (base/app/bower_components/angular-mocks/angular-mocks.js?aa216eb2339283c5ab5aa192023171aa202a2bbd:2746:14)
Run Code Online (Sandbox Code Playgroud)

这是代码:

describe('Example', function() {
  var $q;
  var $rootScope;
  var fakePromise;

  beforeEach(inject(function (_$q_, _$rootScope_) {
    $q = _$q_;
    $rootScope = _$rootScope_;

    fakePromise = function fakePromise(){ …
Run Code Online (Sandbox Code Playgroud)

angularjs karma-runner angular-mock karma-mocha

6
推荐指数
3
解决办法
5385
查看次数

如何在构造函数中使用渲染器测试组件

考虑以下代码:

import {
    Component,
    OnInit,
    Renderer,
    OnDestroy
  } from '@angular/core';

  import { TranslateService } from 'ng2-translate/ng2-translate';

  export class AppComponent implements OnInit, OnDestroy {

  constructor( private translate: TranslateService, renderer: Renderer ) {
    this.globalKeyListenFunc = renderer.listenGlobal('document', 'keydown', (event) => {
      if (event.keyCode === 18) { // ALT-Key
        event.preventDefault();
      }
    });
    ...
  }
Run Code Online (Sandbox Code Playgroud)

如何使用茉莉花测试来测试这样的组件?

我试过以下测试:

describe('App', () => {
  let injector: Injector;
  let backend: MockBackend;
  let connection: MockConnection;
  let translate: TranslateService;
  let renderer: Renderer;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule, TranslateModule.forRoot()],
      providers: [ …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular-mock angular

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

打字稿导入错误的角度

我使用如下语法在我的角度1应用程序(在打字稿中)导入角度

   import * as angular from 'angular';
Run Code Online (Sandbox Code Playgroud)

这导入了角度,angular-mocks而不是来自angular我的ILogService实现失败的角度

./app/shared/Logger.factory.ts(38,7)中的错误:错误TS2420:类'Logger'错误地实现了接口'ILogService'.属性"debug"的类型不兼容.类型'(... argument:any [])=> void'不能分配给'ILogCall'类型.

甚至当我尝试导航到'angular'vscode我得到导航到角嘲笑的角度定义.它应该导航到角度而不是模拟库......

如何避免这个问题?

编辑

以下是实施

我的实现是自定义服务,关于哪些打字稿在编译期间出错(错误被粘贴在上面)

class Logger implements ng.ILogService {
     info(message:string) { //some custom logic in info method}
}

angular.service('logger', Logger)
Run Code Online (Sandbox Code Playgroud)

typescript angular-mock angular

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

匹配所有GET url使用角度模拟后端

我现在正在写一个没有后端ajax的前端.我angular-mocks用来模拟这样的API调用:

$httpBackend.when('GET', '/somelink').respond(function(method, url, data) {
  //do something
});
Run Code Online (Sandbox Code Playgroud)

但是,如果ajax通过params: {id:12345},它将附加到url '/somelink?id=12345'.这并不赶上when('GET', '/somelink')

有没有办法使用RegEx或一些技巧来解决这个问题?只是为了不管里面是什么params,respond()仍然被称为?

谢谢.

更新1:

我不能使用.whenGET,因为我的backendless系统POSTPUT为好.所以我需要保持它的通用性.这两个参数.when('GET', '/somelink')实际上是我代码中的变量.

由于'/somelink'是另一个变量JSON,因此/\/somelink/在JSON中使用RegEx 似乎不起作用.至少那是我现在看到的.

javascript regex ajax angularjs angular-mock

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

使用sinon模拟document.getElemetById('.form').getContext('2d')

我正在使用karma,mocha,chai,sinon和Angular mocks进行单元测试.在我的$ scope.loadChart中,我在canvas标签中绘制了一个图表.我正在使用http://www.chartjs.org/来绘制图表.

Chartjs需要这段代码,document.getElemetById('#canvas').getContext('2d').我如何在Sinon中存根?我的测试坚持这一行.

html unit-testing sinon angularjs angular-mock

5
推荐指数
2
解决办法
3121
查看次数

什么是导入角度模拟的正确方法

版本

typescript: 2.1.4
systemjs: 0.19.41
angular: 1.5.10
angular-mocks: 1.5.10

问题

我试图加载angular-mockssystemjs在打字稿2.0项目.

如果我使用以下它可以工作,但我得到一个TS错误,并{module}在webstorm中也被标记为错误.

import {module} from 'angular-mocks';

describe('someClass', function () {
    'use strict';

    beforeEach(module('someModule'));

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

error TS2305: Module '"/node_modules/@types/angular-mocks/index"' has no exported member 'module'.

我最初只是尝试导入angular-mocks,但导入的angular对象没有mock属性(即使window.angular.mock已定义),因此它会引发错误.

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

describe('someClass', function () {
    'use strict';

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

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

Uncaught TypeError: Cannot read property 'module' of undefined

Systemjs配置

System.config({
    transpiler: 'typescript',
    paths: { …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-mock systemjs

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

如何使用 DOM 测试 angularjs 组件

我正在尝试熟悉测试 AngularJS 应用程序。虽然测试组件逻辑或多或少是清楚的,但我在 html 模板和模型绑定方面遇到了麻烦,因为我想将 html 绑定与控制器的逻辑一起测试。

测试在真实浏览器中由 karma 运行,因此测试环境支持 DOM。

看起来不可能,不是吗?

describe('sign-up', function () {
        angular.mock.module('myApp');
        angular.mock.inject(function($componentController, $rootScope, $document) {
            let scope = $rootScope.$new();
            let signUp = $componentController('signUp', {$scope: scope});
            console.log(`signup = ${signUp}`);
            for (let [k,v] of signUp) {
                // there is no field signUp.firstName
                // but inside the controller code referencing  
                // this.firstName is working
                console.log(`signup.${k} = ${v}`);
            }
            // jquery cannot find #firstName node
            // $('#firstName').val('dan') gets the same outcome
            $document.find('#firstName').val('dan');
            expect($document.find('#firstName').val()).toBe('dan');
            // without DOM form submission …
Run Code Online (Sandbox Code Playgroud)

javascript testing angularjs angular-mock

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