简体   繁体   English

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

[英]Global scope Variable declared is not defined in test spec while testing using jasmine and karma

I have created an Injectable with a declaration for a global variable in the same file to be used. 我在要使用的同一文件中创建了一个带有全局变量声明的Injectable。 I am able to get it working in the code. 我能够在代码中正常工作。 But in my tests the declaration is failing with an undefined error. 但是在我的测试中,声明失败并出现未定义的错误。

declare var myGlobal;

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

I am testing a component and this service is needed as a provider in the testbed for the component testing. 我正在测试组件,该服务需要作为组件测试的测试平台中的提供者。

Following is how it is called: 以下是它的调用方式:

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

    }
    ngOnInit(): void {
        this._h.fileUrl = window.location.href;
        this.getSettings(this._h.settingsSrc);
    }
}

Following is the declaration of the service in the test 以下是测试中服务的声明

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

I have seen this Varaible declared is not defined in spec while testing but is not of help. 我已经看到在测试过程中未在规范中定义声明的Varaible,但没有帮助。

You either declare that global variable within your test file 您可以在测试文件中声明该全局变量

const global = "something";

describe('My test suit', function() {
...
});

or add a Javascript file where it's defined to your karma.conf.js file: 或在您的karma.conf.js文件中添加一个已定义的Javascript文件:

// list of files / patterns to load in the browser //要在浏览器中加载的文件/模式列表

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM