6

嘿,我是 angular 6(又名 angular)测试的新手,我有一个问题是要重新评估我迄今为止看到的每一个测试。

我们先来看一个简单组件的简单测试(由cli生成)

describe('CompComponent', () => {
  let component: CompComponent;
  let fixture: ComponentFixture<CompComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CompComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CompComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

我有一个主要问题:

1.我如何确定每个 Async beforeEach 调用是在每个测试单元(又名它)之前完成的?是否存在这种调用会在每次调用之后发生的情况,因为它毕竟是异步调用?

4

1 回答 1

9

每个都beforeEach将在任何测试开始之前完成。

在您的示例中,compileComponents()是异步的。因此,在这种情况下,我们必须使用 async() 方法。

供您参考,请查看此链接:https ://github.com/angular/angular-cli/issues/4774

为了确保您beforeEach在任何测试开始之前完成,您可以尝试通过添加以下内容来调试您的测试:

compileComponents().then( result => {
  console.log(result);
}

你可以在这一行设置一个断点:console.log(result);你会看到它会在你运行你的测试的时候一直执行,所以如果你在console.log' line and another one in your firt 它的test, you will see you will never get to the second break point before doing theconsole.log`断点一中设置一个断点,这意味着我们将不得不在进行任何测试之前等待 beforeEach 中的任何异步调用。

另一种beforeEach在任何测试开始之前查看意志始终完成的方法是也以这种方式编写测试:

beforeEach(async(() => {
  TestBed.configureTestingModule({
  declarations: [ CompComponent ]
}).compileComponents().then( result => {
    fixture = TestBed.createComponent(CompComponent);
    component = fixture.componentInstance;
  }
}));

您将看到在您的任何测试中fixture都已经可用,这样做。所以你不需要添加另一个 beforeEach 来初始化你的fixture.

要了解更多信息,您可以参考 Stack Overflow 的其他答案:

angular-2-testing-async-function-call-when-to-use

于 2018-10-17T23:49:35.627 回答