environment.ts无法测试Angular 2

问题描述 投票:0回答:1

试图在Angular 2中编写简单的测试,但是如下所示为environment.ts获取错误

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

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();
  });
});

有什么建议吗?

angular typescript karma-jasmine angular-test angular-unit-test
1个回答
0
投票

像这样创建你的**.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();
    }));
});
© www.soinside.com 2019 - 2024. All rights reserved.