首页 > 解决方案 > Jasmine-Karma UnitTest 运行单一与运行所有

问题描述

当我在一个包中运行整个单元测试时,一些测试会失败,尽管单独运行这些测试会成功。我不知道是什么影响了一组跑步。

执行“ng test --code-coverage”命令后,Jasmine-Karma 创建以下输出。

组件 1 - 测试用例 1 = 通过 - 测试用例 2 = 通过 - 测试用例 3 = 通过

组件 2 - 测试用例 1 = 通过 / - 测试用例 2 = 失败 / - 测试用例 3 = 通过 /

例如,如果我只运行 Com2-Case2,它就会通过。

提前致谢。

这是典型的单元测试示例:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { FooterComponent } from './footer.component';

describe('FooterComponent', () => {

    let comp: FooterComponent;
    let fixt: ComponentFixture<FooterComponent>;

    beforeEach(async(() => {

        TestBed.configureTestingModule({

            declarations: [FooterComponent],

            imports: [
                TranslateModule.forRoot(),
            ],

        }).compileComponents();
    }));

    beforeEach(() => {
        fixt = TestBed.createComponent(FooterComponent);
        comp = fixt.componentInstance;
    });

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

});

标签: angularunit-testingkarma-jasmine

解决方案


我通过使用“FakeSync”和“Tick”解决了这个问题。

我意识到如果在测试用例调用中有订阅,它会影响下一个测试用例。为了克服这个问题,Tick 是解决方案。

it('should create TranslationTexts', fakeAsync(() => {
    comp.ngOnInit();
    tick();
    expect(JSON.stringify(comp.translationTexts).length).toBeGreaterThan(0);
}));

Tick 有助于等待异步调用完成。以下资源非常有帮助。

https://codecraft.tv/courses/angular/unit-testing/asynchronous/

谢谢。


推荐阅读