# All files / src/testing unit-test-helper.ts

86.61% Statements 97/112
70% Branches 14/20
82.86% Functions 29/35
86% Lines 86/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277167x
    167x

    167x

    167x
    167x

    167x

    333x

    166x
    1126x

    167x

    159x
    159x

    167x

    176x
    176x
    176x
    176x
    176x

    167x
    79x
    79x
    79x
    79x
    79x

    79x

    79x

    79x
    79x

    167x
    316x
    316x

    167x
    319x
    319x

    167x

    167x

    249x

    167x
    15x
    36x

    167x
    416x

    54x

    416x
    416x

    167x

    449x

    134x

    167x
    48x

    167x

    78x

    167x

    68x

    167x
    89x

    167x

    167x

    114x

    167x
    14x
    56x

    167x
    60x

    167x

    167x

    167x

    167x
    60x
    60x

    167x

    167x
    167x
    12x

    167x
    25x

    167x
    16x
    16x
    19x

    16x

    167x
    12x

    167x

    167x

    167x
     import { LOCALE_ID, TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core';
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { AbstractControl } from '@angular/forms';
    import { By } from '@angular/platform-browser';

    import { I18n } from '@ngx-translate/i18n-polyfill';
    import * as _ from 'lodash';

    import { TableActionsComponent } from '../app/shared/datatable/table-actions/table-actions.component';
    import { CdFormGroup } from '../app/shared/forms/cd-form-group';
    import { Permission } from '../app/shared/models/permissions';
    import {
      PrometheusAlert,
      PrometheusNotification,
      PrometheusNotificationAlert
    } from '../app/shared/models/prometheus-alerts';
    import { _DEV_ } from '../unit-test-configuration';

    export function configureTestBed(configuration, useOldMethod?) {
      if (_DEV_ && !useOldMethod) {
        const resetTestingModule = TestBed.resetTestingModule;
        beforeAll((done) =>
          (async () => {
            TestBed.resetTestingModule();
            TestBed.configureTestingModule(configuration);
            // prevent Angular from resetting testing module
            TestBed.resetTestingModule = () => TestBed;
          })()
            .then(done)
            .catch(done.fail)
        );
        afterAll(() => {
          TestBed.resetTestingModule = resetTestingModule;
        });
      } else {
        beforeEach(async(() => {
          TestBed.configureTestingModule(configuration);
        }));
      }
    }

    export class PermissionHelper {
      tableActions: TableActionsComponent;
      permission: Permission;
      getTableActionComponent: () => TableActionsComponent;

      constructor(permission: Permission, getTableActionComponent: () => TableActionsComponent) {
        this.permission = permission;
        this.getTableActionComponent = getTableActionComponent;
      }

      setPermissionsAndGetActions(
        createPerm: number | boolean,
        updatePerm: number | boolean,
        deletePerm: number | boolean
      ): TableActionsComponent {
        this.permission.create = Boolean(createPerm);
        this.permission.update = Boolean(updatePerm);
        this.permission.delete = Boolean(deletePerm);
        this.tableActions = this.getTableActionComponent();
        return this.tableActions;
      }

      testScenarios({
        fn,
        empty,
        single,
        singleExecuting,
        multiple
      }: {
        fn: () => any;
        empty: any;
        single: any;
        singleExecuting?: any; // uses 'single' if not defined
        multiple?: any; // uses 'empty' if not defined
      }) {
        this.testScenario(
          // 'multiple selections'
          [{}, {}],
          fn,
          _.isUndefined(multiple) ? empty : multiple
        );
        this.testScenario(
          // 'select executing item'
          [{ cdExecuting: 'someAction' }],
          fn,
          _.isUndefined(singleExecuting) ? single : singleExecuting
        );
        this.testScenario([{}], fn, single); // 'select non-executing item'
        this.testScenario([], fn, empty); // 'no selection'
      }

      private testScenario(selection: object[], fn: () => any, expected: any) {
        this.setSelection(selection);
        expect(fn()).toBe(expected);
      }

      setSelection(selection: object[]) {
        this.tableActions.selection.selected = selection;
        this.tableActions.selection.update();
      }
    }

    export class FormHelper {
      form: CdFormGroup;

      constructor(form: CdFormGroup) {
        this.form = form;
      }

      /**
       * Changes multiple values in multiple controls
       */
      setMultipleValues(values: { [controlName: string]: any }, markAsDirty?: boolean) {
        Object.keys(values).forEach((key) => {
          this.setValue(key, values[key], markAsDirty);
        });
      }

      /**
       * Changes the value of a control
       */
      setValue(control: AbstractControl | string, value: any, markAsDirty?: boolean): AbstractControl {
        control = this.getControl(control);
        if (markAsDirty) {
          control.markAsDirty();
        }
        control.setValue(value);
        return control;
      }

      private getControl(control: AbstractControl | string): AbstractControl {
        if (typeof control === 'string') {
          return this.form.get(control);
        }
        return control;
      }

      /**
       * Change the value of the control and expect the control to be valid afterwards.
       */
      expectValidChange(control: AbstractControl | string, value: any, markAsDirty?: boolean) {
        this.expectValid(this.setValue(control, value, markAsDirty));
      }

      /**
       * Expect that the given control is valid.
       */
      expectValid(control: AbstractControl | string) {
        // 'isValid' would be false for disabled controls
        expect(this.getControl(control).errors).toBe(null);
      }

      /**
       * Change the value of the control and expect a specific error.
       */
      expectErrorChange(
        control: AbstractControl | string,
        value: any,
        error: string,
        markAsDirty?: boolean
      ) {
        this.expectError(this.setValue(control, value, markAsDirty), error);
      }

      /**
       * Expect a specific error for the given control.
       */
      expectError(control: AbstractControl | string, error: string) {
        expect(this.getControl(control).hasError(error)).toBeTruthy();
      }
    }

    export class FixtureHelper {
      fixture: ComponentFixture<any>;

      constructor(fixture: ComponentFixture<any>) {
        this.fixture = fixture;
      }

      /**
       * Expect a list of id elements to be visible or not.
       */
      expectIdElementsVisible(ids: string[], visibility: boolean) {
        ids.forEach((css) => {
          this.expectElementVisible(`#${css}`, visibility);
        });
      }

      /**
       * Expect a specific element to be visible or not.
       */
      expectElementVisible(css: string, visibility: boolean) {
        expect(Boolean(this.getElementByCss(css))).toBe(visibility);
      }

      expectFormFieldToBe(css: string, value: string) {
        const props = this.getElementByCss(css).properties;
        expect(props['value'] || props['checked'].toString()).toBe(value);
      }

      clickElement(css: string) {
        this.getElementByCss(css).triggerEventHandler('click', null);
        this.fixture.detectChanges();
      }

      getText(css: string) {
        const e = this.getElementByCss(css);
        return e ? e.nativeElement.textContent.trim() : null;
      }

      getElementByCss(css: string) {
        this.fixture.detectChanges();
        return this.fixture.debugElement.query(By.css(css));
      }
    }

    export class PrometheusHelper {
      createAlert(name, state = 'active', EtimeMultiplier = 1) {
        return {
          fingerprint: name,
          status: { state },
          labels: {
            alertname: name
          },
          annotations: {
            summary: `${name} is ${state}`
          },
          generatorURL: `http://${name}`,
          startsAt: new Date(new Date('2022-02-22').getTime() * timeMultiplier).toString()
        } as PrometheusAlert;
      }

      createNotificationAlert(name, status = 'firing') {
        return {
          status: status,
          labels: {
            alertname: name
          },
          annotations: {
            summary: `${name} is ${status}`
          },
          generatorURL: `http://${name}`
        } as PrometheusNotificationAlert;
      }

      createNotification(alertNumber = 1, status = 'firing') {
        const alerts = [];
        for (let i = 0; i < alertNumber; i++) {
          alerts.push(this.createNotificationAlert('alert' + i, status));
        }
        return { alerts, status } as PrometheusNotification;
      }

      createLink(url) {
        return `<a href="${url}" target="_blank"><i class="fa fa-line-chart"></i></a>`;
      }
    }

    const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
    <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
      <file source-language="en" datatype="plaintext" original="ng2.template">
        <body>
        </body>
      </file>
    </xliff>
    `;

    const i18nProviders = [
      { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
      { provide: TRANSLATIONS, useValue: XLIFF },
      { provide: LOCALE_ID, useValue: 'en' },
      I18n
    ];

    export { i18nProviders };