标签: karma-jasmine

如何用茉莉花测试John papa vm.model单元测试?

我使用John papa angular style guide我的控制器看起来像:

遵循风格约翰爸爸风格控制器风格指南:

function testController() {

    var vm = this;

    vm.model = { name: "controllerAs vm test" };
}
Run Code Online (Sandbox Code Playgroud)

我的测试代码如下:

describe('Controller: testController', function () {

    beforeEach(module('myApp'));

    var testController;

    beforeEach(inject(function ($controller) {
        scope = {};

        testController = $controller('testController', {
        });

    }));

    it('should have vm.model defined and testController.vm.model is equal to controllerAs vm test', function () { 
        expect(testController.vm).toBeDefined();  
        expect(testController.vm.model).toBeDefined();     
        expect(testController.vm.model.name).toEqual("controllerAs vm test");
    });
});
Run Code Online (Sandbox Code Playgroud)

结果:

测试失败:结果消息:预期未定义要定义.在堆栈

所以我的问题是我们如何测试vm.model和其他变量呢?我没有在指南中找到适当的指导线:控制器

unit-testing jasmine angularjs angularjs-scope karma-jasmine

20
推荐指数
2
解决办法
8800
查看次数

茉莉是应该按照声明的顺序或以随机顺序执行规范吗?

取消评论最后一个规格.一切都崩溃了......为什么?

describe('test', function() {
  var index = 1;

  it('test 1', function() {
    expect(index).toBe(1);
    index++;
  });

  it('test 2', function() {
    expect(index).toBe(2);
    index++;
  });

  it('test 3', function() {
    expect(index).toBe(3);
    index++;
  });

  it('test 4', function() {
    expect(index).toBe(4);
    index++;
  });

  it('test 5', function() {
    expect(index).toBe(5);
    index++;
  });

  it('test 6', function() {
    expect(index).toBe(6);
    index++;
  });

  it('test 7', function() {
    expect(index).toBe(7);
    index++;
  });

  it('test 8', function() {
    expect(index).toBe(8);
    index++;
  });

  it('test 9', function() {
    expect(index).toBe(9);
    index++;
  });

  it('test 10', function() {
    expect(index).toBe(10);
    index++;
  });

  // it('test …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jasmine karma-jasmine

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

Karma webpack输出多个"webpack:等到捆绑完成"

在最近发布的webpack 1.14.0/karma 1.4.0/karma-webpack 2.2.0之后,当karma开始其webpack构建时,我现在看到了很多这些消息.

webpack: wait until bundle finished:
Run Code Online (Sandbox Code Playgroud)

有时我看到多达6-8个,他们似乎正在使构建更长.例如,这个:

Hash: 255562a2a96fffe34fae
Version: webpack 1.14.0
Time: 408ms
webpack: bundle is now VALID.
webpack: bundle is now INVALID.
webpack: wait until bundle finished:
webpack: wait until bundle finished:
webpack: wait until bundle finished:
webpack: wait until bundle finished:
webpack: wait until bundle finished:
webpack: wait until bundle finished:
ts-loader: Using typescript@2.1.5 and C:\git\project\tsconfig.json
Run Code Online (Sandbox Code Playgroud)

到目前为止,它还没有阻止我的构建,但至少它似乎现在已经锁定,即使是暂时的.其他人看到这个?如果它是我的结果,我想要清理它,但正如我所说,我的配置文件没有改变,但现在已经出现了最近发布的karma/webpack系列产品过去3周.

我的问题是:

  1. 这条消息是什么意思?
  2. 如何解决创建它们的问题?

karma-runner karma-jasmine webpack karma-webpack

20
推荐指数
2
解决办法
6570
查看次数

Angular mock $ httpBackend给出没有待处理的请求

按照angularJS $ httpBackend的官方指南,我会做这个测试,但是Karma给我这个错误: Error: No pending request to flush ! at Function.$httpBackend.flush

测试

'use strict';

describe('profileCtrl', function () {
var scope, $httpBackend;

beforeEach(angular.mock.module('maap'));
beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){

    $httpBackend = _$httpBackend_;
    $httpBackend.when('GET', 'profile').respond([{id: 1, name: 'Bob'}]);
    scope = $rootScope.$new();
    $controller('profileCtrl', {$scope: scope});
}))

it('should fetch list of users', function(){
    $httpBackend.flush();
    expectGET(scope.current_user.length).toBe(1);
    expect(scope.current_user[0].name).toBe('Bob');
});
Run Code Online (Sandbox Code Playgroud)

});

这个简单的控制器:

'use strict';

 angular.module('maap').controller('profileCtrl', function($scope, UserService) {

$scope.current_user = UserService.details(0);
Run Code Online (Sandbox Code Playgroud)

});

angularjs karma-jasmine

19
推荐指数
2
解决办法
3万
查看次数

如何在angular2单元测试中更改选择框的值?

我有一个Angular2组件,其中包含一个看起来像的选择框

<select [(ngModel)]="envFilter" class="form-control" name="envSelector" (ngModelChange)="onChangeFilter($event)">
    <option *ngFor="let env of envs" [ngValue]="env">{{env}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我正在尝试为ngModelChange事件编写单元测试.这是我最近的失败尝试

it("should filter and show correct items", async(() => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        el = fixture.debugElement.query(By.name("envSelector"));
        fixture.detectChanges();
        makeResponse([hist2, longhist]);
        comp.envFilter = 'env3';
        el.triggerEventHandler('change', {});
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            expect(comp.displayedHistory).toEqual(longhist);
        });
    });
Run Code Online (Sandbox Code Playgroud)

我遇到问题的部分是更改底层模型的值comp.envFilter = 'env3';不会触发更改方法.我补充说el.triggerEventHandler('change', {});但是这个抛出了Failed: Uncaught (in promise): ReferenceError: By is not defined.我在文档中找不到任何提示......任何想法?

unit-testing typescript karma-jasmine angular2-testing angular

19
推荐指数
3
解决办法
2万
查看次数

Angular 2错误:在Karma-Jasmine测试中没有Http的提供者

即使我的应用程序完美运行且没有错误,我仍然在我的业力测试中收到以下错误.据说没有Http的提供者.我import { HttpModule } from '@angular/http';在app.module.ts文件中使用并将其添加到imports数组中.业力错误如下所示:

Chrome 52.0.2743 (Mac OS X 10.12.0) App: TrackBudget should create the app FAILED
    Failed: Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: No provider for Http!
    Error: No provider for Http!
        at NoProviderError.Error (native)
        at NoProviderError.BaseError [as constructor] (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/facade/errors.js:24:0 <- src/test.ts:2559:34)
        at NoProviderError.AbstractProviderError [as constructor] (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/di/reflective_errors.js:42:0 <- src/test.ts:15415:16)
        at new NoProviderError (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/di/reflective_errors.js:73:0 <- src/test.ts:15446:16)
        at ReflectiveInjector_._throwOrNull (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/di/reflective_injector.js:761:0 <- src/test.ts:26066:19)
        at ReflectiveInjector_._getByKeyDefault (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/di/reflective_injector.js:789:0 <- src/test.ts:26094:25)
        at ReflectiveInjector_._getByKey (webpack:/Users/ChrisGaona%201/budget-tracking/~/@angular/core/src/di/reflective_injector.js:752:0 <- src/test.ts:26057:25)
        at …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular

19
推荐指数
3
解决办法
4万
查看次数

Angular2快速入门教程打破了Karma测试 - "无法绑定到'ngModel',因为它不是'input'的已知属性."

在尝试TDD时,我正在关注官方的Angular"Hero"快速入门教程.

https://angular.io/docs/ts/latest/tutorial/toh-pt1.html

一旦我到达替换步骤:

<input value="{{hero.name}}" placeholder="name">
Run Code Online (Sandbox Code Playgroud)

<input [(ngModel)]="hero.name" placeholder="name">
Run Code Online (Sandbox Code Playgroud)

我的Karma测试运行器抛出以下错误:

错误:模板解析错误:无法绑定到'ngModel',因为它不是'input'的已知属性.("name:] [(ngModel)] ="hero.name"占位符="名称">"):AppComponent @ 6:23预期未定义要定义.

但是,应用程序按预期工作,我在控制台中看不到任何错误.(而且我相当自信我正确地遵循了教程,看不到任何拼写错误等)

我的app.components.ts看起来像:

import { Component } from '@angular/core';

export class Hero {
    id: number;
    name: string;
}

@Component({
    selector: 'my-app',
    template: `
            <h1>{{title}}</h1>
            <h2>{{hero.name}} details!</h2>
            <div><label>id: </label>{{hero.id}}</div>
            <div>
                <label>name: </label>
                <input [(ngModel)]="hero.name" placeholder="name">
            </div>
    `
})

export class AppComponent {
    title = 'Tour of Heroes';
    hero: Hero = {
        id: 1,
        name: 'Windstorm'
    };
}
Run Code Online (Sandbox Code Playgroud)

我的app.module看起来像:

import { NgModule }      from '@angular/core';
import { …
Run Code Online (Sandbox Code Playgroud)

karma-runner karma-jasmine ngmodel angular

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

Karma --auto-watch不再有效

我的Karma安装用于自动监视 - 当我保存.js文件时,它会重新运行测试.自从我做了任何JavaScript以来已经有几个月了,现在我再来使用它,自动监视功能无效.这是我的karma.conf:

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '../',


        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],


        // list of files / patterns to load in the browser
        files: [
          'jQuery/jquery-1.10.2.js',
          'jasmine/jasmine.js',
          'jasmine-jquery/jasmine-jquery.js',
          'Angular/angular.js',
          'Angular/angular-route.js',
          'Angular/angular-mocks.js',
          'Angular/angular-animate.min.js',
          'Angular/angular-sanitize.min.js',
          'Angular/angular-cache.min.js',
          'emcommon.js',
          'Moment/moment.js',
          'ViewModels/Common/*.js',
          'ViewModels/Settings/*.js',
          'Tests/Common/*.js',
          'Tests/Settings/*.js',
        ],

        // list of files to exclude
        exclude: [
        ],


        // preprocess matching files before serving them …
Run Code Online (Sandbox Code Playgroud)

javascript jasmine angularjs karma-runner karma-jasmine

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

instance [output.propName] .subscribe不是polyfill产生的函数

我遇到了一个奇怪的问题.我已经研究了这个错误,它通常似乎与@Outputor 的使用有关EventEmitter,但在这里并非如此.

如果我有一个特定的polyfill,我的应用程序中会出现以下错误:

TypeError: instance[output.propName].subscribe is not a function
    at createDirectiveInstance (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:12319:71)
    at createViewNodes (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:13776:38)
    at callViewAction (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:14210:1)
    at execComponentViewsAction (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:14119:1)
    at createViewNodes (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:13804:1)
    at createRootView (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:13665:1)
    at callWithDebugContext (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:15090:26)
    at Object.debugCreateRootView [as createRootView] (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:14373:1)
    at ComponentFactory_.webpackJsonp.../../../core/esm5/core.js.ComponentFactory_.create (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/core.js:11260:26)
    at initComponent (http://localhost:9876/_karma_webpack_/webpack:/Users/stuart/localhost/projects/tt-new/work-group/node_modules/@angular/core/esm5/testing.js:1137:1)
Run Code Online (Sandbox Code Playgroud)

polyfill如下:

Object.prototype.clone = function(deep = false) {
    return (deep)
        ? JSON.parse(JSON.stringify(this)) // Deep clone - copies object property values in full.
        : Object.assign({}, this);         // Shallow clone - copies property values (including object references rather …
Run Code Online (Sandbox Code Playgroud)

typescript karma-jasmine angular

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

等待ngOnInit在Jasmine Angular2中完成

我正在对一个组件进行单元测试,这就是我所拥有的:

describe('Component: nav', () => {

  beforeEach(() => addProviders([
    provide(UserService, {useClass: MockUserService}),
    NavComponent
  ]));

  it('should have a property \'firstName\' with the value \'Crazypug\'',
    async(inject([NavComponent], (component) => {
      component.ngOnInit();
      expect(component.firstName).toEqual('Crazypug')
    }))
  );

});
Run Code Online (Sandbox Code Playgroud)

这是ngOnInit函数:

ngOnInit() {
    this.userService.getFirstNameCall().subscribe(
      data => {this.firstName = data.firstname; });
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我得到:

预期未定义为等于'Crazypug'

我怎样才能让Jasmine等待ngOnInit函数完成?我从很久以前就在SO上找到了一些解决方案(以角度2的方式).他们非常复杂或过时.

jasmine karma-jasmine angular

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