使用 jasmine 和 karma 进行测试时,声明的全局范围变量未在测试规范中定义

Gar*_*ary 0 testing components jasmine karma-runner angular

我创建了一个 Injectable,其中包含要使用的同一文件中的全局变量的声明。我能够让它在代码中工作。但在我的测试中,声明失败并出现未定义的错误。

declare var myGlobal;

@Injectable()
export class HttpService {
  constructor() {
    console.log(myGlobal);
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在测试一个组件,并且需要此服务作为组件测试的测试台中的提供者。

以下是它的调用方式:

    @Component({
    ...
    })
    export class AppComponent {
    constructor(_h: HttpService) {

    }
    ngOnInit(): void {
        this._h.fileUrl = window.location.href;
        this.getSettings(this._h.settingsSrc);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是测试中服务的声明

beforeEach(async(() => {
    const settingsFile = 'json';
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        MenubarComponent,
      ],
      imports: [
        HttpClientModule,
      ],
      providers: [
        HttpService
      ],
    }).compileComponents();}))


it('getSettings() tests', inject([HttpService], async(async (_h: HttpService) => {
     const cmp = new AppComponent(_h);
     await cmp.ngOnInit(); // this is where the service function is trigered
}))
Run Code Online (Sandbox Code Playgroud)

我在测试时看到这个声明的变量没有在规范中定义,但没有帮助。

Anu*_*ara 5

您可以在测试文件中声明该全局变量

const global = "something";

describe('My test suit', function() {
...
});
Run Code Online (Sandbox Code Playgroud)

或者将 Javascript 文件添加到您的karma.conf.js文件中:

// 要在浏览器中加载的文件/模式列表

files: [
   ...,
   'global-variable.js'
],
Run Code Online (Sandbox Code Playgroud)