【问题标题】:Is there a way to have a base class for Jasmine Unit Tests (Angular 4)?有没有办法为 Jasmine 单元测试(Angular 4)创建一个基类?
【发布时间】:2017-07-12 16:31:57
【问题描述】:

我有几个 .spec.ts 文件都需要以下 beforeEach:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, HttpModule, CovalentHttpModule.forRoot({
        interceptors: [{
          interceptor: CustomInterceptorService, paths: ['**'],
        }],
      }),],
      declarations: [LoginComponent],
      providers: [AuthService, { provide: Router, useClass: class { navigate = jasmine.createSpy('navigate'); } }, LoggingService, CustomInterceptorService],
    })
      .compileComponents();
  }));

有没有办法将此 TestBed 配置外包?现在我必须使用相同的导入和提供程序来调整每个新的测试文件。

我正在寻找类似基本单元测试的东西。茉莉花可以吗?

【问题讨论】:

  • by base class 你到底是什么意思

标签: javascript angular unit-testing typescript jasmine


【解决方案1】:

这个案例并不是 Jasmine 所特有的。如果要复用一个函数,可以通过 JavaScript/TypeScript 来实现。

辅助函数:

export const setupFooTestbed = async(() => {
    TestBed.configureTestingModule({...})...
});
...
beforeEach(setupFooTestbed);

或者它可以是TestModuleMetadata 对象的基类,被TestBed.configureTestingModule 接受:

export FooTestModuleMetadata implements TestModuleMetadata { ... }
...
beforeEach(async(() => {
    TestBed.configureTestingModule(new FooTestModuleMetadata)...
}));

或者可以提供一个通用的测试模块给initTestEnvironment method

使用编译器工厂、PlatformRef 和 A​​ngular 模块初始化测试环境。这些对于套件中的每个测试都是通用的。

这只能被调用一次,为当前平台上的当前测试套件设置通用提供程序。如果您绝对需要更改提供程序,请先使用 resetTestEnvironment。

【讨论】:

  • 这正是我想要的。谢谢
猜你喜欢
  • 2016-01-02
  • 2017-11-18
  • 2017-10-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 2020-09-23
相关资源
最近更新 更多