运行ng测试会抛出许多错误并失败

时间:2017-03-10 10:06:15

标签: angularjs unit-testing jasmine karma-jasmine typescript2.0

angular-cli v1.0.0 beta.21
typescript version 2.0.10

目前,我正在使用这两个版本的typescript和angular-cli。 当我运行ng test时,我收到了这些错误 -

  1. 错误:没有Http的提供商! enter image description here
  2. 无法绑定到' ngModel'因为它不是“输入”的已知属性。 enter image description here
  3. app-navbar不是已知元素 enter image description here
  4. 以下是app.module.ts的源代码

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import {HttpModule, JsonpModule} from '@angular/http';
    import { AppComponent } from './app.component';
    import { NavbarComponent } from './navbar/navbar.component';
    import { IndexComponent } from './index/index.component';
    import { ResultsComponent } from './results/results.component';
    import {Routes, RouterModule, Router} from '@angular/router';
    import {SearchService} from './search.service';
    import { NotFoundComponent } from './not-found/not-found.component';
    import {CommonModule} from '@angular/common';
    import { AdvancedsearchComponent } from './advancedsearch/advancedsearch.component';
    import {StoreDevtoolsModule} from '@ngrx/store-devtools';
    import {StoreModule} from '@ngrx/store';
    import {reducer} from './reducers/index';
    import { SearchBarComponent } from './search-bar/search-bar.component';
    
    const appRoutes: Routes = [
    {path: 'search', component: ResultsComponent},
    {path: '', component: IndexComponent},
    {path: '404', component: NotFoundComponent},
    {path: '**', redirectTo: '/404'},
    ];
    @NgModule({
    declarations: [
    AppComponent,
    NavbarComponent,
    IndexComponent,
    ResultsComponent,
    NotFoundComponent,
    AdvancedsearchComponent,
    SearchBarComponent
    ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpModule,
    JsonpModule,
    RouterModule.forRoot(appRoutes),
    StoreModule.provideStore(reducer),
    StoreDevtoolsModule.instrumentOnlyWithExtension(),
    ],
    providers: [SearchService],
    bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    search.service.spec.ts

    /* tslint:disable:no-unused-variable */
    
    import { TestBed, async, inject } from '@angular/core/testing';
    import { SearchService } from './search.service';
    
    describe('SearchService', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({
          providers: [SearchService]
        });
      });
    
      it('should ...', inject([SearchService], (service: SearchService) => {
        expect(service).toBeTruthy();
      }));
    });
    

    search.component.spec.ts

    /* tslint:disable:no-unused-variable */
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { DebugElement } from '@angular/core';
    
    import { SearchBarComponent } from './search-bar.component';
    
    describe('SearchBarComponent', () => {
      let component: SearchBarComponent;
      let fixture: ComponentFixture<SearchBarComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ SearchBarComponent ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(SearchBarComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });
    

    results.component.spec.ts

     /* tslint:disable:no-unused-variable */
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { DebugElement } from '@angular/core';
    
    import { ResultsComponent } from './results.component';
    
    describe('ResultsComponent', () => {
      let component: ResultsComponent;
      let fixture: ComponentFixture<ResultsComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ ResultsComponent ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(ResultsComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });
    

    results.component.html

    <app-navbar></app-navbar>
        <div class="container">
            <!-- Start ignoring BootLintBear -->
            <div class="row">
                <div class="col-md-offset-1">
                    <!-- Stop ignoring BootLintBear -->
                </div>
                <div class="col-md-11">
                    <div class="btn-group" id="search-options">
                        <button type="button" class="btn btn-default" [class.active_view]="Display('all')" (click)="docClick()">
                            All
                        </button>
                        <button type="button" class="btn btn-default" [class.active_view]="Display('images')" (click)="imageClick()">Images</button>
                        <button type="button" class="btn btn-default" [class.active_view]="Display('videos')" (click)="videoClick()">Videos</button>
                        <div class="btn-group">
                            <button type="button" class="btn btn-default" id="tools" data-toggle="collapse" data-target="#search-tools">
                                Tools <span class="caret"></span></button>
                        </div>
                    </div>
                    <div class="collapse" id="search-tools">
                        <button class="btn btn-default" (click)="filterByContext()" type="button"> Context Ranking</button>
                        <button class="btn btn-default" (click)="filterByDate()" type="button"> Sort by Date</button>
                        <button class="btn btn-default" data-toggle="modal" data-target="#myModal" (click)="advancedsearch()" type="button"> Advanced Search</button>
                    </div>
                    <hr>
                    <div class="container-fluid" id="progress-bar">
                        {{message}}
                    </div>
                    <div class="text-result" *ngIf="Display('all')">
                        <div *ngFor="let item of items$|async" class="result">
                            <div class="title">
                                <a href="{{item.link}}">{{item.title}}</a>
                            </div>
                            <div class="link">
                                <p>{{item.link}}</p>
                            </div>
                            <div>
                                {{item.pubDate|date:'fullDate'}}
                            </div>
                        </div>
                    </div>
                    <div class="image-result" *ngIf="Display('images')">
                        <div *ngFor="let item of items$|async">
                            <img class="res-img" src="{{item.link}}">
                        </div>
                    </div>
                    <div class="video-result" *ngIf="Display('videos')">
                        <div *ngFor="let item of items" class="result">
                            <div class="title">
                                <a href="{{item.path}}">{{item.title}}</a>
                            </div>
                            <div class="link">
                                <p>{{item.link}}</p>
                            </div>
                        </div>
                    </div>
                    <br>
                    <div class="pagination-property">
                        <nav aria-label="Page navigation">
                            <ul class="pagination" id="pag-bar">
                                <li class="page-item"><span class="page-link" href="#" (click)="decPresentPage()">Previous</span></li>
                                <li class="page-item" *ngFor="let num of getNumber(maxPage)"><span class="page-link"
                                                                                 *ngIf="presentPage>=4 && num<=noOfPages"
                                                                                 [class.active_page]="getStyle(presentPage-3+num)"
                                                                                 (click)="getPresentPage(presentPage-3+num)"
                                                                                 href="#">{{presentPage-3+num}}</span>
                                    <span class="page-link" *ngIf="presentPage<4 && num<=noOfPages" [class.active_page]="getStyle(num)"
                      (click)="getPresentPage(num)" href="#">{{num+1}}</span></li>
                                <li class="page-item"><span class="page-link" (click)="incPresentPage()">Next</span></li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <app-advancedsearch></app-advancedsearch>
        </div>
    

    package.json

    {
      "name": "susper",
      "version": "0.0.0",
      "license": "MIT",
      "angular-cli": {},
      "scripts": {
        "start": "ng serve",
        "lint": "tslint \"src/**/*.ts\"",
        "test": "ng test",
        "pree2e": "webdriver-manager update",
        "e2e": "protractor"
      },
      "private": true,
      "dependencies": {
        "@angular/common": "2.4.0",
        "@angular/compiler": "2.4.0",
        "@angular/core": "2.4.0",
        "@angular/forms": "2.4.0",
        "@angular/http": "2.4.0",
        "@angular/platform-browser": "2.4.0",
        "@angular/platform-browser-dynamic": "2.4.0",
        "@angular/router": "3.4.0",
        "@ngrx/core": "^1.2.0",
        "@ngrx/effects": "^2.0.0",
        "@ngrx/router-store": "^1.2.5",
        "@ngrx/store": "^2.2.1",
        "@ngrx/store-devtools": "^3.2.3",
        "core-js": "^2.4.1",
        "ngrx-store-freeze": "^0.1.6",
        "reselect": "^2.5.4",
        "rxjs": "5.0.0-beta.12",
        "ts-helpers": "^1.1.1",
        "typescript": "2.0.10",
        "zone.js": "^0.6.23"
      },
      "devDependencies": {
        "@angular/cli": "^1.0.0-rc.1",
        "@angular/compiler-cli": "2.4.0",
        "@types/jasmine": "2.5.38",
        "@types/node": "^6.0.42",
        "angular-cli": "1.0.0-beta.24",
        "codelyzer": "~2.0.0-beta.1",
        "jasmine-core": "2.5.2",
        "jasmine-spec-reporter": "2.5.0",
        "karma": "1.2.0",
        "karma-chrome-launcher": "^2.0.0",
        "karma-cli": "^1.0.1",
        "karma-jasmine": "^1.0.2",
        "karma-remap-istanbul": "^0.2.1",
        "protractor": "4.0.9",
        "ts-node": "1.2.1",
        "tslint": "^4.0.2",
        "typescript": "~2.0.3",
        "webdriver-manager": "10.2.5"
      }
    }
    

    我很快就需要帮助,我已经搜索了很多关于它的信息。根据消息来源做了更改,但我仍然遇到这些错误。现在我只剩下这个选项,在Stack-overflow上发布它。这些错误仅在我运行ng test时发生。另外,我在Stack溢出时遇到了与此相关的问题,并更新了我的打字稿版本和angular-cli版本。我已经开始编写版本了。感谢您抽出时间来解答这个问题:)

2 个答案:

答案 0 :(得分:1)

克服并解决所有错误 - 导入所有模块 -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {HttpModule, JsonpModule} from '@angular/http';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { IndexComponent } from './index/index.component';
import { ResultsComponent } from './results/results.component';
import {Routes, RouterModule, Router} from '@angular/router';
import {SearchService} from './search.service';
import { NotFoundComponent } from './not-found/not-found.component';
import {CommonModule} from '@angular/common';
import { AdvancedsearchComponent } from './advancedsearch/advancedsearch.component';
import {StoreDevtoolsModule} from '@ngrx/store-devtools';
import {StoreModule} from '@ngrx/store';
import {reducer} from './reducers/index';
import { SearchBarComponent } from './search-bar/search-bar.component';
每个.component.spec.ts中的

。这样做,ng test将正常运行而不会出现任何错误。

答案 1 :(得分:0)

  1. 您需要在规范中导入 HttpClientTestingModule 文件。
  2. 您需要在规范文件中导入 ReactiveFormsModule、FormsModule。
  3. 我假设 app-navbar 是您可能在 shared.module 中定义的可重用组件,因此您需要在规范文件中导入 SharedModule。

应将上述所有导入添加到引发错误的规范文件中。