【问题标题】:Testing Component or Sevice containing "declare var" with Jest使用 Jest 测试包含“declare var”的组件或服务
【发布时间】:2019-12-08 06:58:08
【问题描述】:

在测试我的组件或服务时出现错误

ReferenceError: flagPath 未定义

flagPath 来自资产文件夹中的 config.js 文件。有没有办法将它添加到TestBed?

我正在使用 jest,但我不确定在哪里添加它。我已经在 karma 中读过,您可以将其添加到 Var 文件中......

//imports...
declare var flagPath: string;

@Injectable({
    providedIn: 'root'
})
export class Service {
   constructor(private http: HttpClient) {}
   getMaxContent(): Observable < any > {
       return this.http.get(flagPath);
   }

在我的测试中,所有的测试都是真实的,见下文:

let service: Service;
beforeEach(async(() = > {
    TestBed.configureTestingModule({
        schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
        declarations: [
            OverviewComponent,
        ],
        imports: [],
        providers: [Service, HttpClient],
    }).compileComponents();
}));

beforeEach(() = > {
    fixture = TestBed.createComponent(OverviewComponent);
    service = fixture.debugElement.injector.get(Service);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', async() = > {
    component.ngOnInit();
    fixture.whenStable();
    expect(component).toBeTruthy();
});

【问题讨论】:

    标签: angular testing jestjs config


    【解决方案1】:

    我显然通过使用全局“声明”使这变得复杂,因此我重构了代码并删除了“声明” 相反,我在服务中对 url 进行了编码。这解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2019-08-29
      • 2017-10-27
      • 2021-08-08
      • 2022-06-10
      • 2018-11-30
      • 2022-10-25
      相关资源
      最近更新 更多