全局范围 在使用茉莉花和业力进行测试时,声明的变量未在测试规范中定义



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

declare var myGlobal;
@Injectable()
export class HttpService {
  constructor() {
    console.log(myGlobal);
  }
}

我正在测试一个组件,需要此服务作为组件测试平台中的提供程序。

以下是它的称呼方式:

    @Component({
    ...
    })
    export class AppComponent {
    constructor(_h: HttpService) {
    }
    ngOnInit(): void {
        this._h.fileUrl = window.location.href;
        this.getSettings(this._h.settingsSrc);
    }
}

以下是测试中服务的声明

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

我已经看到这个 Varaible 声明在测试时没有在规范中定义,但没有帮助。

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

const global = "something";
describe('My test suit', function() {
...
});

或者添加一个 Javascript 文件,其中定义了它的 karma.conf.js 文件:

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

files: [
   ...,
   'global-variable.js'
],

最新更新