角度4单元测试(TestBed)非常慢

时间:2017-12-07 09:28:54

标签: angular performance unit-testing testbed

我使用Angular TestBed进行了一些单元测试。即使测试非常简单,它们也会非常慢(每秒平均1次测试) 即使在重新阅读Angular文档之后,我也找不到性能如此糟糕的原因。
隔离测试,不使用TestBed,只需几秒钟即可完成。

单元测试

import { Component } from "@angular/core";
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { DebugElement } from "@angular/core";
import { DynamicFormDropdownComponent } from "./dynamicFormDropdown.component";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { FormsModule } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";
import { TranslateService } from "@ngx-translate/core";
import { TranslatePipeMock } from "../../../../tests-container/translate-pipe-mock";

describe("Component: dynamic drop down", () => {

    let component: DynamicFormDropdownComponent;
    let fixture: ComponentFixture<DynamicFormDropdownComponent>;
    let expectedInputQuestion: DropdownQuestion;
    const emptySelectedObj = { key: "", value: ""};

    const expectedOptions = {
        key: "testDropDown",
        value: "",
        label: "testLabel",
        disabled: false,
        selectedObj: { key: "", value: ""},
        options: [
            { key: "key_1", value: "value_1" },
            { key: "key_2", value: "value_2" },
            { key: "key_3", value: "value_3" },
        ],
    };

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [NgbModule.forRoot(), FormsModule],
            declarations: [DynamicFormDropdownComponent, TranslatePipeMock],
            providers: [TranslateService],
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(DynamicFormDropdownComponent);

        component = fixture.componentInstance;

        expectedInputQuestion = new DropdownQuestion(expectedOptions);
        component.question = expectedInputQuestion;
    });

    it("should have a defined component", () => {
        expect(component).toBeDefined();
    });

    it("Must have options collapsed by default", () => {
        expect(component.optionsOpen).toBeFalsy();
    });

    it("Must toggle the optionsOpen variable calling openChange() method", () => {
        component.optionsOpen = false;
        expect(component.optionsOpen).toBeFalsy();
        component.openChange();
        expect(component.optionsOpen).toBeTruthy();
    });

    it("Must have options available once initialized", () => {
        expect(component.question.options.length).toEqual(expectedInputQuestion.options.length);
    });

    it("On option button click, the relative value must be set", () => {
        spyOn(component, "propagateChange");

        const expectedItem = expectedInputQuestion.options[0];
        fixture.detectChanges();
        const actionButtons = fixture.debugElement.queryAll(By.css(".dropdown-item"));
        actionButtons[0].nativeElement.click();
        expect(component.question.selectedObj).toEqual(expectedItem);
        expect(component.propagateChange).toHaveBeenCalledWith(expectedItem.key);
    });

    it("writeValue should set the selectedObj once called (pass string)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem.key);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });

    it("writeValue should set the selectedObj once called (pass object)", () => {
        expect(component.question.selectedObj).toEqual(emptySelectedObj);
        const expectedItem = component.question.options[0];
        component.writeValue(expectedItem);
        expect(component.question.selectedObj).toEqual(expectedItem);
    });
});

目标组件(带模板)

import { Component, Input, OnInit, ViewChild, ElementRef, forwardRef } from "@angular/core";
import { FormGroup, ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { DropdownQuestion } from "../../element/question/questionDropdown";

@Component({
    selector: "df-dropdown",
    templateUrl: "./dynamicFormDropdown.component.html",
    styleUrls: ["./dynamicFormDropdown.styles.scss"],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DynamicFormDropdownComponent),
            multi: true,
        },
    ],
})
export class DynamicFormDropdownComponent implements ControlValueAccessor {
    @Input()
    public question: DropdownQuestion;

    public optionsOpen: boolean = false;

    public selectItem(key: string, value: string): void {
        this.question.selectedObj = { key, value };
        this.propagateChange(this.question.selectedObj.key);
    }

    public writeValue(object: any): void {
        if (object) {
            if (typeof object === "string") {
                this.question.selectedObj = this.question.options.find((item) => item.key === object) || { key: "", value: "" };
            } else {
                this.question.selectedObj = object;
            }
        }
    }

    public registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    public propagateChange = (_: any) => { };

    public registerOnTouched() {
    }

    public openChange() {
        if (!this.question.disabled) {
            this.optionsOpen = !this.optionsOpen;
        }
    }

    private toggle(dd: any) {
        if (!this.question.disabled) {
            dd.toggle();
        }
    }
}

-----------------------------------------------------------------------

<div>
    <div (openChange)="openChange();" #dropDown="ngbDropdown" ngbDropdown class="wrapper" [ngClass]="{'disabled-item': question.disabled}">
        <input type="text" 
                [disabled]="question.disabled" 
                [name]="controlName" 
                class="select btn btn-outline-primary" 
                [ngModel]="question.selectedObj.value | translate"
                [title]="question.selectedObj.value"
                readonly ngbDropdownToggle #selectDiv/>
        <i (click)="toggle(dropDown);" [ngClass]="optionsOpen ? 'arrow-down' : 'arrow-up'" class="rchicons rch-003-button-icon-referenzen-pfeil-akkordon"></i>
        <div ngbDropdownMenu aria-labelledby="dropdownBasic1" class="option-wrapper">
            <button *ngFor="let opt of question.options; trackBy: opt?.key" (click)="selectItem(opt.key, opt.value); dropDown.close();"
                class="dropdown-item option" [disabled]="question.disabled">{{opt.value | translate}}</button>
        </div>
    </div>
</div>

Karma config

var webpackConfig = require('./webpack/webpack.dev.js');

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-webpack'),
      require('karma-jasmine'),
      require('karma-phantomjs-launcher'),
      require('karma-sourcemap-loader'),
      require('karma-tfs-reporter'),
      require('karma-junit-reporter'),
    ],

    files: [
      './app/polyfills.ts',
      './tests-container/test-bundle.spec.ts',
    ],
    exclude: [],
    preprocessors: {
      './app/polyfills.ts': ['webpack', 'sourcemap'],
      './tests-container/test-bundle.spec.ts': ['webpack', 'sourcemap'],
      './app/**/!(*.spec.*).(ts|js)': ['sourcemap'],
    },
    webpack: {
      entry: './tests-container/test-bundle.spec.ts',
      devtool: 'inline-source-map',
      module: webpackConfig.module,
      resolve: webpackConfig.resolve
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },

    reporters: ['progress', 'junit', 'tfs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    concurrency: Infinity
  })
}

9 个答案:

答案 0 :(得分:17)

事实证明,问题在于Github

上的Angular

根据Github讨论的解决方法,将运行测试的时间从40秒减少到1秒!

const oldResetTestingModule = TestBed.resetTestingModule;

beforeAll((done) => (async () => {
  TestBed.resetTestingModule();
  TestBed.configureTestingModule({
    // ...
  });

  function HttpLoaderFactory(http: Http) {
    return new TranslateHttpLoader(http, "/api/translations/", "");
  }

  await TestBed.compileComponents();

  // prevent Angular from resetting testing module
  TestBed.resetTestingModule = () => TestBed;
})()
  .then(done)
  .catch(done.fail));

答案 1 :(得分:3)

弗朗切斯科的上述答案很不错,但最后需要此代码。否则,其他测试套件将失败。

    afterAll(() => {
        TestBed.resetTestingModule = oldResetTestingModule;
        TestBed.resetTestingModule();
    });

答案 2 :(得分:2)

MasterDetailPage

创建新文件:

describe('Test name', () => {
    configureTestSuite();

    beforeAll(done => (async () => {
       TestBed.configureTestingModule({
            imports: [HttpClientTestingModule, NgReduxTestingModule],
            providers: []
       });
       await TestBed.compileComponents();

    })().then(done).catch(done.fail));

    it(‘your test', (done: DoneFn) => {

    });
});

答案 3 :(得分:1)

您可能想尝试ng-bullet。 它大大提高了Angular单元测试的执行速度。 还建议将其用于有关测试台单元测试性能的官方角度回购问题:https://github.com/angular/angular/issues/12409#issuecomment-425635583

重点是替换每个测试文件标题中的原始 beforeEach

beforeEach(async(() => {
        // a really simplified example of TestBed configuration
        TestBed.configureTestingModule({
            declarations: [ /*list of components goes here*/ ],
            imports: [ /* list of providers goes here*/ ]
        })
        .compileComponents();
  }));

使用 configureTestSuite

import { configureTestSuite } from 'ng-bullet';
...
configureTestSuite(() => {
    TestBed.configureTestingModule({
        declarations: [ /*list of components goes here*/ ],
        imports: [ /* list of providers goes here*/ ]
    })
});

答案 4 :(得分:1)

2020年10月更新

将angular应用程序升级到Angular 9 可以改善测试运行时间


如果您希望使用最新版本,则以下软件包可帮助我提高测试性能:

伍兹子弹 link

Ng-Bullet是一个库,可通过Angular TestBed增强您的单元测试体验,从而大大提高测试的执行速度。

它将要做的是,它不会一直创建测试套件,而是使用以前创建的套件,通过使用它,我看到了300%的测试运行。

Ref

答案 5 :(得分:0)

这可能取决于您用于测试的浏览器。对于我来说,ChromeHeadless明显更快(〜1分钟):

ng test --single-run --browsers ChromeHeadless

比PhantomJS(〜3分钟):

ng test --single-run --browsers PhantomJS

答案 6 :(得分:0)

我做了一个小功能,可以用来加快速度。其效果类似于其他答案中提到的ng-bullet,但仍会清理测试之间的服务,以使它们不会泄漏状态。该函数为precompileForTests,可在n-ng-dev-utils中使用。

像这样使用它(来自其文档):

// let's assume `AppModule` declares or imports a `HelloWorldComponent`
precompileForTests([AppModule]);

// Everything below here is the same as normal. Just add the line above.

describe("AppComponent", () => {
  it("says hello", async () => {
    TestBed.configureTestingModule({ declarations: [HelloWorldComponent] });
    await TestBed.compileComponents(); // <- this line is faster
    const fixture = TestBed.createComponent(HelloWorldComponent);
    expect(fixture.nativeElement.textContent).toContain("Hello, world!");
  });
});

答案 7 :(得分:0)

Yoav Schniederman的答案对我很有帮助。要补充,我们需要清理<style>标签中的<head>,因为它们也导致内存泄漏。清理afterAll()中的所有样式也可以改善性能。

请阅读original post供参考

答案 8 :(得分:0)

在我的特定情况下,它会延迟,因为我们在组件样式“component.component.scss”中导入了 style.scss(也导入了其他巨大的样式),这会为每个组件模板生成递归样式。

为避免这种情况,请仅在组件中导入 scss 变量、mixin 和类似内容。