Импорт содержимого данных локального файла в другой угловой компонент - PullRequest
0 голосов
/ 27 сентября 2019

У меня есть некоторые ложные данные в empiricial-percentiles.mock.ts file.Я пытаюсь получить доступ к этим данным в 2 других файлах empirical-percentiles.component.spec.ts и empiricial-percentiles.stories.ts.

Вот мой код для файла empiricial-процентtiles.mock.ts


export const EmpiricalPercentiles = {
  empiricalPercentiles: [
    {
      empiricalPercentile: 99,
      yearlyValueDailyDeviation: 40,
    },
    {
      empiricalPercentile: 95,
      yearlyValueDailyDeviation: 35,
    },
    {
      empiricalPercentile: 90,
      yearlyValueDailyDeviation: 30,
    },
    {
      empiricalPercentile: 75,
      yearlyValueDailyDeviation: 25,
    },
    {
      empiricalPercentile: 50,
      yearlyValueDailyDeviation: 20,
    },
    {
      empiricalPercentile: 25,
      yearlyValueDailyDeviation: 15,
    },
    {
      empiricalPercentile: 10,
      yearlyValueDailyDeviation: 10,
    },
    {
      empiricalPercentile: 5,
      yearlyValueDailyDeviation: 5,
    },
    {
      empiricalPercentile: 1,
      yearlyValueDailyDeviation: 1,
    },
  ],
};

Вот мой код для файла empirical -centtiles.component.spec.ts

import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClient, HttpClientModule } from '@angular/common/http';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateLoader, TranslateModule, TranslateParser, TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { Configuration, HoldingsControllerService, Snapshot } from '@trp/gdx-product-rest-client';
import { ErrorMessageModule } from '@trp/gdx-wc-branding';
import { EmpiricalPercentiles } from './empirical-percentiles';

import {
  ConfigurationService,
  DateTimeFormattingService,
  I18nLabelService,
  NumberFormattingService,
  TranslateCustomParser,
} from '@trp/gdx-wc-core-services';
import { DateSelectorTableModule, TableModule } from '@trp/gdx-wc-layout';
import { DynamicModule } from 'ng-dynamic-component';
import { of } from 'rxjs';
import { EmpiricalPercentilesComponent } from './empirical-percentiles.component';
import { HttpMockRequestInterceptorService } from '.storybook/HttpMockRequestInterceptor.service';

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json');
}

// const empiricalPercentiles = {
//   empiricalPercentiles: [
//     {
//       empiricalPercentile: 99,
//       yearlyValueDailyDeviation: 40,
//     },
//     {
//       empiricalPercentile: 95,
//       yearlyValueDailyDeviation: 35,
//     },
//     {
//       empiricalPercentile: 90,
//       yearlyValueDailyDeviation: 30,
//     },
//     {
//       empiricalPercentile: 75,
//       yearlyValueDailyDeviation: 25,
//     },
//     {
//       empiricalPercentile: 50,
//       yearlyValueDailyDeviation: 20,
//     },
//     {
//       empiricalPercentile: 25,
//       yearlyValueDailyDeviation: 15,
//     },
//     {
//       empiricalPercentile: 10,
//       yearlyValueDailyDeviation: 10,
//     },
//     {
//       empiricalPercentile: 5,
//       yearlyValueDailyDeviation: 5,
//     },
//     {
//       empiricalPercentile: 1,
//       yearlyValueDailyDeviation: 1,
//     },
//   ],
// };

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [EmpiricalPercentilesComponent],
      imports: [
        CommonModule,
        DateSelectorTableModule,
        ErrorMessageModule,
        TableModule,
        DynamicModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient],
          },
          parser: {
            provide: TranslateParser,
            useClass: TranslateCustomParser,
          },
        }),
      ],
      providers: [
        NumberFormattingService,
        DateTimeFormattingService,
        HttpClient,
        TranslateService,
        ConfigurationService,
        I18nLabelService,
        HoldingsControllerService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpMockRequestInterceptorService,
          multi: true,
        },
        {
          provide: Configuration,
          useFactory: ConfigurationService.getSwaggerRestConfig,
          deps: [ConfigurationService],
          multi: false,
        },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EmpiricalPercentilesComponent);
    component = fixture.componentInstance;
    component.productCode = 'COMP245';
    component.vehicle = Snapshot.VehicleTypeEnum.ETFFUND;
    HttpMockRequestInterceptorService.setInterceptValues([
      {
        // tslint:disable-next-line:max-line-length
        urlToIntercept: `NOT_DEFINED/v1/product/audience/institutional/country/us/language/en/product/COMP245/empirical-percentiles-exhibit`,
        jsonReplacement: component.productCode ? empiricalPercentiles : null,
        jsonFunction: null,
      },
    ]);
    fixture.detectChanges();
  });

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

Вот мой код для empirical-pertiles.stories.ts

import { HTTP_INTERCEPTORS, HttpClient, HttpParams } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { TranslateLoader, TranslateModule, TranslateParser, TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { select, text, withKnobs } from '@storybook/addon-knobs';
import { moduleMetadata, storiesOf } from '@storybook/angular';
import { Configuration, HoldingsControllerService, Snapshot } from '@trp/gdx-product-rest-client';
import { ConfigurationService, Locale, TranslateCustomParser } from '@trp/gdx-wc-core-services';
import { LocaleService } from '@trp/gdx-wc-core-services';
import { HoldingsModule } from '../../holdings.module';
import { EmpiricalPercentilesComponent } from './empirical-percentiles.component';
import { HttpMockRequestInterceptorService } from '.storybook/HttpMockRequestInterceptor.service';
import { EmpiricalPercentiles } from './empirical-percentiles';

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json');
}

let locale = Locale.EN_GLOBAL;
@NgModule()
export class EmpiricalPercentilesStoriesComponent {
  constructor(private translate: TranslateService, private localeService: LocaleService) {
    localeService.languageObservable().subscribe((language) => {
      translate.use(language);
    });
    localeService.locale = locale;
  }
}

storiesOf('Product/Product Details/Holdings/Portfolio Tracking', module)
  .addDecorator(withKnobs)
  .addDecorator(
    moduleMetadata({
      imports: [
        HoldingsModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient],
          },
          parser: {
            provide: TranslateParser,
            useClass: TranslateCustomParser,
          },
        }),
      ],
      schemas: [],
      providers: [
        ConfigurationService,
        HoldingsControllerService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpMockRequestInterceptorService,
          multi: true,
        },
        {
          provide: Configuration,
          useFactory: ConfigurationService.getSwaggerRestConfig,
          deps: [ConfigurationService],
          multi: false,
        },
      ],
    }),
  )
  .add('Empirical Percentile Table', () => {
    const productCode = text('Product code', 'COMP245');
    const vehicle = text('Vehicle', Snapshot.VehicleTypeEnum.ETFFUND);
    locale = select('Locale', Locale, Locale.EN_GLOBAL as any);

    HttpMockRequestInterceptorService.setInterceptValues([
      {
        urlToIntercept: `NOT_DEFINED/v1/product/audience/institutional/country/us/language/en/product/${productCode}/empirical-percentiles-exhibit`,
        jsonReplacement: {},
        jsonFunction: productCode ? getEmpiricalPercentilesData : null,
      },
    ]);

    return {
      template: `
      <gdx-empirical-percentiles
        [productCode] = "productCode"
        [vehicle] = "vehicle">
      </gdx-empirical-percentiles>`,
      component: EmpiricalPercentilesComponent,
      props: {
        productCode,
        vehicle,
      },
    };
  });
export function getEmpiricalPercentilesData(params: HttpParams) {
  return {
    EmpiricalPercentiles,
    // empiricalPercentiles: [
    //   {
    //     empiricalPercentile: 99,
    //     yearlyValueOfDailyDeviation: 40,
    //   },
    //   {
    //     empiricalPercentile: 95,
    //     yearlyValueOfDailyDeviation: 35,
    //   },
    //   {
    //     empiricalPercentile: 90,
    //     yearlyValueOfDailyDeviation: 30,
    //   },
    //   {
    //     empiricalPercentile: 75,
    //     yearlyValueOfDailyDeviation: 25,
    //   },
    //   {
    //     empiricalPercentile: 50,
    //     yearlyValueOfDailyDeviation: 20,
    //   },
    //   {
    //     empiricalPercentile: 25,
    //     yearlyValueOfDailyDeviation: 15,
    //   },
    //   {
    //     empiricalPercentile: 10,
    //     yearlyValueOfDailyDeviation: 10,
    //   },
    //   {
    //     empiricalPercentile: 5,
    //     yearlyValueOfDailyDeviation: 5,
    //   },
    //   {
    //     empiricalPercentile: 1,
    //     yearlyValueOfDailyDeviation: 1,
    //   },
    // ],
  };
}

Как получить фиктивные данные как в файле спецификации, так и в файле истории, чтобы мне не нужно было вручную хранить эти данные в обоих файлах

1 Ответ

0 голосов
/ 27 сентября 2019

вам нужно экспортировать вашу константу в empiricial-проценттилях.mock.ts

export const empiricalPercentiles = {...}

и импортировать туда, куда вы хотите.

import {empiricalPercentiles} from 'empiricial-percentiles.mock.ts';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...