【问题标题】:Async beforeEach finished before/after each test unit(it)Async beforeEach 在每个测试单元之前/之后完成(它)
【发布时间】:2019-03-22 16:48:01
【问题描述】:

嘿,我是 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 调用是在每个测试单元(又名它)之前完成的?是否存在这种调用会在每次调用之后发生的情况,因为它毕竟是异步调用?

【问题讨论】:

    标签: angular jasmine karma-jasmine angular-test testbed


    【解决方案1】:

    每个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 ittest, 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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多