【问题标题】:environment.ts not working in testing Angular 2environment.ts 在测试 Angular 2 时不起作用
【发布时间】:2019-02-17 02:53:13
【问题描述】:

尝试在 Angular 2 中编写简单的测试,但出现environment.ts 的错误,如下所示

./web/environments/environment.ts 中的错误模块构建失败:错误: web\environments\environment.ts 是 TypeScript 编译中缺少。请确保它在 您的 tsconfig 通过 'files' 或 'include' 属性。

app.component.ts

import { Component} from '@angular/core';
import { environment } from '../environments/environment';

@Component({
  selector: 'web-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'Test App'; 

  constructor() {
    console.log(environment);
  }  
}

app.component.spec.ts

import { AppComponent } from './app.component';

describe('AppComponent', () => {
  it(`should 1+1`, () => {
    expect(1 + 1).toEqual(2);  //Success
  });
  it('should have component ', () => {
    const component = new AppComponent();  //Throws error
    // expect(component).toBeTruthy();
  });
});

有什么建议吗?

【问题讨论】:

  • 这是因为 ng serve 和 ng test 使用不同的 tsconfig.json。你能发布你的 tsconfig.spec.json 吗?
  • 我只有tsconfig.json,但没有tsconfig.spec.json。我已经使用 Angular CLI 创建了项目。
  • 查看 src 文件夹

标签: angular typescript karma-jasmine angular-test angular-unit-test


【解决方案1】:

像这样创建你的**.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppModule } from './app/app.module';
import { APP_BASE_HREF } from '@angular/common';

describe('App', () => {
    beforeEach(() => {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
        TestBed.configureTestingModule({
            declarations: [
                AppComponent
            ],
            imports: [
                AppModule
            ],
            providers: [
                { provide: APP_BASE_HREF, useValue: '/' }
            ]
        });
    });

    it('should have component', async(() => {
        let fixture = TestBed.createComponent(AppComponent);
        let app = fixture.debugElement.componentInstance;
        expect(app).toBeTruthy();
    }));
});

【讨论】:

  • 获取Error: Illegal state: Could not load the summary for directive AppComponent.
  • 正在修改答案,希望对您有所帮助
猜你喜欢
  • 1970-01-01
  • 2017-05-25
  • 2017-01-19
  • 2017-07-23
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
相关资源
最近更新 更多