@angular/core/testing#inject TypeScript Examples

The following examples show how to use @angular/core/testing#inject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: not-friend.guard.spec.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
describe('NotFriendGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [NotFriendGuard]
    });
  });

  it('should ...', inject([NotFriendGuard], (guard: NotFriendGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #2
Source File: auth.guard.spec.ts    From Uber-ServeMe-System with MIT License 6 votes vote down vote up
describe('AuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuard]
    });
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #3
Source File: auth.service.spec.ts    From muino-time-management with GNU General Public License v3.0 6 votes vote down vote up
describe('AuthService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthService]
    });
  });

  it('should be created', inject([AuthService], (service: AuthService) => {
    expect(service).toBeTruthy();
  }));
});
Example #4
Source File: home.component.spec.ts    From litefy with MIT License 6 votes vote down vote up
describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let userService;
  let browseService;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      imports: [AppModule]
    })
      .compileComponents();
  }));

  beforeEach(inject([SpotifyUserService, SpotifyBrowseService], (s, b) => {
    userService = s;
    browseService = b;
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Example #5
Source File: auth.guard.spec.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
describe('AuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuard]
    });
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #6
Source File: dialog-host.component.spec.ts    From mysteryofthreebots with Apache License 2.0 6 votes vote down vote up
describe('DialogHostComponent', () => {
  let component: DialogHostComponent;
  let fixture: ComponentFixture<DialogHostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DialogHostComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DialogHostComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should close dialog on clickng backdrop', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'close');
      fixture.debugElement.nativeElement.querySelector('.app-dialog-backdrop').click();
      expect(dialogService.close).toHaveBeenCalled();
    }
  ));
});
Example #7
Source File: stock-market.service.spec.ts    From enterprise-ng-2020-workshop with MIT License 6 votes vote down vote up
describe('StockMarketService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [StockMarketService]
    });
  });

  it('should be created', inject(
    [StockMarketService],
    (service: StockMarketService) => {
      expect(service).toBeTruthy();
    }
  ));

  it('should return expected result', inject(
    [StockMarketService],
    (service: StockMarketService) => {
      const expectedStock: any = {
        symbol: 'TSLA',
        primaryExchange: 'Nasdaq',
        latestPrice: '124',
        change: '1',
        changePercent: '0.81'
      };

      service.retrieveStock('TSLA').subscribe((stock) => {
        expect(stock.symbol).toBe(expectedStock.symbol);
        expect(stock.exchange).toBe(expectedStock.primaryExchange);
        expect(stock.changePercent).toBe(expectedStock.changePercent);
        expect(stock.last).toBe(expectedStock.latestPrice);
      }, fail);
    }
  ));
});
Example #8
Source File: logout.guard.spec.ts    From ewelink-web-ui with MIT License 6 votes vote down vote up
describe('LogoutGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LogoutGuard]
    });
  });

  it('should ...', inject([LogoutGuard], (guard: LogoutGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #9
Source File: ngx-mat-datefns-date-adapter.spec.ts    From ngx-mat-datefns-date-adapter with MIT License 6 votes vote down vote up
describe('NgxDateFnsDateAdapter with MAT_DATE_LOCALE override', () => {
  let adapter: NgxDateFnsDateAdapter;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [NgxMatDateFnsDateModule],
        providers: [
          { provide: MAT_DATE_LOCALE, useValue: 'da' },
          { provide: NGX_MAT_DATEFNS_LOCALES, useValue: [da] },
        ],
      }).compileComponents();
    })
  );

  beforeEach(inject([DateAdapter], (d: NgxDateFnsDateAdapter) => {
    adapter = d;
  }));

  it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => {
    const expectedValue = [
      'søndag',
      'mandag',
      'tirsdag',
      'onsdag',
      'torsdag',
      'fredag',
      'lørdag',
    ];

    expect(adapter.getDayOfWeekNames('long')).toEqual(expectedValue);
  });
});
Example #10
Source File: app.effects.spec.ts    From tzcolors with MIT License 6 votes vote down vote up
describe('AppEffects', () => {
  let actions$: Observable<any>
  let effects: AppEffects

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AppEffects, provideMockActions(() => actions$)],
    })

    effects = TestBed.inject(AppEffects)
  })

  it('should be created', () => {
    expect(effects).toBeTruthy()
  })
})
Example #11
Source File: login.guard.spec.ts    From Uber-ServeMe-System with MIT License 6 votes vote down vote up
describe('LoginGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LoginGuard]
    });
  });

  it('should ...', inject([LoginGuard], (guard: LoginGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #12
Source File: connection.service.spec.ts    From RcloneNg with MIT License 6 votes vote down vote up
describe('Service: Connection', () => {
	beforeEach(() => {
		TestBed.configureTestingModule({
			providers: [ConnectionService],
		});
	});

	it('should ...', inject([ConnectionService], (service: ConnectionService) => {
		expect(service).toBeTruthy();
	}));
});
Example #13
Source File: auth.guard.spec.ts    From barista with Apache License 2.0 6 votes vote down vote up
describe('AuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientModule],
      providers: [AuthService, AuthGuard],
    }).compileComponents();
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #14
Source File: chat.service.spec.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
describe('ChatService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ChatService],
    });
  });

  it('should ...', inject([ChatService], (service: ChatService) => {
    expect(service).toBeTruthy();
  }));
});
Example #15
Source File: auth-guard.guard.spec.ts    From NetCoreTutes with MIT License 6 votes vote down vote up
describe('AuthGuardGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuardGuard]
    });
  });

  it('should ...', inject([AuthGuardGuard], (guard: AuthGuardGuard) => {
    expect(guard).toBeTruthy();
  }));
});
Example #16
Source File: status-bar.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('Status Bar', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StatusBarModule],
      declarations: [TestComponent],
    });

    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should match snapshot', fakeAsync(() => {
    expect(fixture).toMatchSnapshot();

    const chunk = fixture.debugElement.query(
      By.css('aui-status-bar .aui-status-bar__chunk'),
    ).nativeElement as HTMLElement;
    chunk.dispatchEvent(new Event('mouseenter'));
    tick(50);

    fixture.detectChanges();
    expect(fixture).toMatchSnapshot();
    expect(ocEl).toMatchSnapshot();
  }));

  it('should onChunkClick called once', () => {
    const mockFn = jest.fn();

    fixture.componentInstance.onChunkClick = mockFn;

    const chunk = fixture.debugElement.query(
      By.css('aui-status-bar .aui-status-bar__chunk'),
    ).nativeElement as HTMLElement;
    chunk.dispatchEvent(new Event('click'));

    expect(mockFn.mock.calls.length).toBe(1);
    expect(mockFn.mock.calls[0][0]).toEqual({
      scale: 0.1,
      type: StatusType.Info,
      class: 'custom-class',
    });
  });
});
Example #17
Source File: ngx-mat-datefns-date-adapter.spec.ts    From ngx-mat-datefns-date-adapter with MIT License 5 votes vote down vote up
describe('NgxDateFnsDateAdapter with NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS override', () => {
  describe('use UTC', () => {
    let adapter: NgxDateFnsDateAdapter;

    beforeEach(
      waitForAsync(() => {
        TestBed.configureTestingModule({
          imports: [NgxMatDateFnsDateModule],
          providers: [
            {
              provide: NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS,
              useValue: { useUtc: true },
            },
          ],
        }).compileComponents();
      })
    );

    beforeEach(inject([DateAdapter], (d: NgxDateFnsDateAdapter) => {
      adapter = d;
    }));

    it('should create date in UTC', () => {
      const expectedDate = parseJSON('2017-01-02T00:00:00Z');
      expect(adapter.createDate(2017, JAN, 2)).toEqual(expectedDate);
    });

    it('should create today in UTC', () => {
      const today = new Date();
      const todayUTCString = `${today.getFullYear()}-${(today.getMonth() + 1)
        .toString()
        .padStart(2, '0')}-${today
        .getDate()
        .toString()
        .padStart(2, '0')}T00:00:00Z`;
      const expectedDate = parseJSON(todayUTCString);
      expect(adapter.today()).toEqual(expectedDate);
    });

    it('should parse dates to UTC', () => {
      const expectedDate = parseJSON('2017-01-02T00:00:00Z');
      expect(adapter.parse('1/2/2017', 'MM/dd/yyyy')).toEqual(expectedDate);
    });

    it('should return UTC date when deserializing', () => {
      const expectedDate = parseJSON('2020-04-12T23:20:50.52Z');
      expect(adapter.deserialize('2020-04-12T23:20:50.52Z')).toEqual(
        expectedDate
      );
    });
  });
});
Example #18
Source File: home.component.spec.ts    From ledge with Mozilla Public License 2.0 5 votes vote down vote up
describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        SharedModule,
        PeriodicTableModule,
        RouterTestingModule,
        HttpClientTestingModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: TranslateFakeLoader,
          },
        }),
      ],
      declarations: [HomeComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should update category', () => {
    const category = 'sourceMgr';

    component.setCurrentAtomCategory(category);

    expect(component.category).toBe(category);
  });

  it('should get data', () => {
    inject([HttpTestingController], (httpMock: HttpTestingController) => {
      component.ngAfterViewInit();

      const fisrt = httpMock.expectOne('./assets/periodic-table.json');
      const req = httpMock.expectOne(
        'https://api.github.com/repos/phodal/ledge/contributors'
      );
      expect(req.request.method).toEqual('GET');
      req.flush([]);

      httpMock.verify();
    });
  });
});
Example #19
Source File: message.service.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('MessageService', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  let messageService: MessageService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TestModule],
      providers: [
        {
          provide: MESSAGE_CONFIG,
          useValue: {
            duration: 10_000,
            maxStack: 3,
          },
        },
      ],
    });

    fixture = TestBed.createComponent(TestComponent);

    inject(
      [OverlayContainer, MessageService],
      (overlayContainer: OverlayContainer, service: MessageService) => {
        ocEl = overlayContainer.getContainerElement();
        messageService = service;
      },
    )();
  });

  it('should work with global config', () => {
    messageService.success('Message success0');
    fixture.detectChanges();
    messageService.success('Message success1');
    fixture.detectChanges();
    messageService.success('Message success2');
    fixture.detectChanges();
    messageService.success('Message success3');
    fixture.detectChanges();
    messageService.success('Message success4');
    fixture.detectChanges();
    messageService.success('Message success5');
    fixture.detectChanges();

    expect(ocEl.querySelectorAll('.aui-message').length).toEqual(6);
  });

  it('should show a success Message with  string', () => {
    messageService.success('Message success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-message')).not.toBeNull();
    expect(ocEl.querySelector('.aui-message').classList).toContain(
      'aui-message--success',
    );
    expect(ocEl.querySelector('.aui-message__content').innerHTML).toContain(
      'Message success',
    );
  });

  it('should show a success Message with object', () => {
    messageService.success({
      content: 'Message success object',
      duration: 5,
    });
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-message')).not.toBeNull();
    expect(ocEl.querySelector('.aui-message').classList).toContain(
      'aui-message--success',
    );
    expect(ocEl.querySelector('.aui-message__content').innerHTML).toContain(
      'Message success object',
    );
  });
});
Example #20
Source File: ngx-mat-datefns-date-adapter.spec.ts    From ngx-mat-datefns-date-adapter with MIT License 4 votes vote down vote up
describe('NgxDateFnsDateAdapter', () => {
  let adapter: NgxDateFnsDateAdapter;
  let assertValidDate: (d: Date | null, valid: boolean) => void;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [NgxMatDateFnsDateModule],
      }).compileComponents();
    })
  );

  beforeEach(inject([DateAdapter], (dateAdapter: NgxDateFnsDateAdapter) => {
    adapter = dateAdapter;

    assertValidDate = (d: Date | null, valid: boolean) => {
      expect(adapter.isDateInstance(d)).not.toBeNull(
        `Expected ${d} to be a date instance`
      );
      expect(adapter.isValid(d as Date)).toBe(
        valid,
        `Expected ${d} to be ${valid ? 'valid' : 'invalid'},` +
          ` but was ${valid ? 'invalid' : 'valid'}`
      );
    };
  }));

  it('should get year', () => {
    expect(adapter.getYear(new Date(2017, JAN, 1))).toBe(2017);
  });

  it('should get month', () => {
    expect(adapter.getMonth(new Date(2017, JAN, 1))).toBe(0);
  });

  it('should get number of days in a month', () => {
    expect(adapter.getNumDaysInMonth(new Date(2017, JAN, 1))).toBe(31);
    expect(adapter.getNumDaysInMonth(new Date(2016, FEB, 1))).toBe(29);
  });

  it('should get date', () => {
    expect(adapter.getDate(new Date(2017, JAN, 1))).toBe(1);
  });

  it('should get day of week', () => {
    expect(adapter.getDayOfWeek(new Date(2017, JAN, 1))).toBe(0);
  });

  it('should get long month names', () => {
    expect(adapter.getMonthNames('long')).toEqual([
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ]);
  });

  it('should get short month names', () => {
    expect(adapter.getMonthNames('short')).toEqual([
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ]);
  });

  it('should get narrow month names', () => {
    expect(adapter.getMonthNames('narrow')).toEqual([
      'J',
      'F',
      'M',
      'A',
      'M',
      'J',
      'J',
      'A',
      'S',
      'O',
      'N',
      'D',
    ]);
  });

  it('should get month names in a different locale', () => {
    adapter.setLocale(ja);
    expect(adapter.getMonthNames('long')).toEqual([
      '1月',
      '2月',
      '3月',
      '4月',
      '5月',
      '6月',
      '7月',
      '8月',
      '9月',
      '10月',
      '11月',
      '12月',
    ]);
  });

  it('should get date names', () => {
    expect(adapter.getDateNames()).toEqual([
      '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',
    ]);
  });

  it('should get long day of week names', () => {
    expect(adapter.getDayOfWeekNames('long')).toEqual([
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    ]);
  });

  it('should get short day of week names', () => {
    expect(adapter.getDayOfWeekNames('short')).toEqual([
      'Sun',
      'Mon',
      'Tue',
      'Wed',
      'Thu',
      'Fri',
      'Sat',
    ]);
  });

  it('should get narrow day of week names', () => {
    expect(adapter.getDayOfWeekNames('narrow')).toEqual([
      'S',
      'M',
      'T',
      'W',
      'T',
      'F',
      'S',
    ]);
  });

  it('should get day of week names in a different locale', () => {
    adapter.setLocale(ja);
    expect(adapter.getDayOfWeekNames('long')).toEqual([
      '日曜日',
      '月曜日',
      '火曜日',
      '水曜日',
      '木曜日',
      '金曜日',
      '土曜日',
    ]);
  });

  it('should get year name', () => {
    expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017');
  });

  it('should get first day of week', () => {
    expect(adapter.getFirstDayOfWeek()).toBe(0);
  });

  it('should create Date', () => {
    expect(adapter.createDate(2017, JAN, 1)).toEqual(new Date(2017, JAN, 1));
  });

  it('should not create Date with month over/under-flow', () => {
    expect(() => adapter.createDate(2017, DEC + 1, 1)).toThrow();
    expect(() => adapter.createDate(2017, JAN - 1, 1)).toThrow();
  });

  it('should not create Date with date over/under-flow', () => {
    expect(() => adapter.createDate(2017, JAN, 32)).toThrow();
    expect(() => adapter.createDate(2017, JAN, 0)).toThrow();
  });

  it('should create Date with low year number', () => {
    expect(adapter.createDate(-1, JAN, 1).getFullYear()).toBe(-1);
    expect(adapter.createDate(0, JAN, 1).getFullYear()).toBe(0);
    expect(adapter.createDate(50, JAN, 1).getFullYear()).toBe(50);
    expect(adapter.createDate(99, JAN, 1).getFullYear()).toBe(99);
    expect(adapter.createDate(100, JAN, 1).getFullYear()).toBe(100);
  });

  it("should get today's date", () => {
    expect(adapter.sameDate(adapter.today(), new Date())).toBe(
      true,
      "should be equal to today's date"
    );
  });

  it('should parse string', () => {
    expect(adapter.parse('1/1/2017', 'dd/MM/yyyy')).toEqual(
      new Date(2017, JAN, 1)
    );
  });

  it('should parse number', () => {
    const timestamp = new Date().getTime();
    expect(adapter.parse(timestamp, 'dd/MM/yyyy')).toEqual(new Date(timestamp));
  });

  it('should parse Date', () => {
    const date = new Date(2017, JAN, 1);
    expect(adapter.parse(date, 'dd/MM/yyyy')).toEqual(date);
    expect(adapter.parse(date, 'dd/MM/yyyy')).not.toBe(date);
  });

  it('should parse undefined as null', () => {
    expect(adapter.parse(undefined, 'dd/MM/yyyy')).toBeNull();
  });

  it('should parse [] as null', () => {
    expect(adapter.parse([], 'dd/MM/yyyy')).toBeNull();
  });

  it('should parse invalid value as invalid', () => {
    const d = adapter.parse('hello', 'dd/MM/yyyy');
    expect(d).not.toBeNull();
    expect(adapter.isDateInstance(d)).toBe(
      true,
      'Expected string to have been fed through Date.parse'
    );
    expect(adapter.isValid(d as Date)).toBe(
      false,
      'Expected to parse as "invalid date" object'
    );
  });

  it('should format', () => {
    expect(adapter.format(new Date(2017, JAN, 1), 'd/d/yyyy')).toEqual(
      '1/1/2017'
    );
  });

  it('should format with custom format', () => {
    expect(adapter.format(new Date(2017, JAN, 1), 'MMMM d, yyyy')).toEqual(
      'January 1, 2017'
    );
  });

  it('should format with a different locale', () => {
    adapter.setLocale(ja);
    expect(adapter.format(new Date(2017, JAN, 1), 'yyyy/d/d')).toEqual(
      '2017/1/1'
    );
  });

  it('should throw when attempting to format invalid date', () => {
    expect(() => adapter.format(new Date(NaN), 'd/d/yyyy')).toThrowError(
      /Invalid time value/
    );
  });

  it('should throw when attempting to set locale via string without providing NGX_MAT_DATEFNS_LOCALES token', () => {
    expect(() => adapter.setLocale('invalid')).toThrowError(
      /locale 'invalid' does not exist in locales array. Add it to the NGX_MAT_DATEFNS_LOCALES token./
    );
  });

  it('should throw when attempting to load null locale', () => {
    // @ts-expect-error - Argument of type 'Date | null' is not assignable to parameter of type 'Date'.
    expect(() => adapter.setLocale(null)).toThrowError(
      /setLocale should be called with the string locale code or date-fns Locale object/
    );
  });

  it('should add years', () => {
    expect(adapter.addCalendarYears(new Date(2017, JAN, 1), 1)).toEqual(
      new Date(2018, JAN, 1)
    );
    expect(adapter.addCalendarYears(new Date(2017, JAN, 1), -1)).toEqual(
      new Date(2016, JAN, 1)
    );
  });

  it('should respect leap years when adding years', () => {
    expect(adapter.addCalendarYears(new Date(2016, FEB, 29), 1)).toEqual(
      new Date(2017, FEB, 28)
    );
    expect(adapter.addCalendarYears(new Date(2016, FEB, 29), -1)).toEqual(
      new Date(2015, FEB, 28)
    );
  });

  it('should add months', () => {
    expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), 1)).toEqual(
      new Date(2017, FEB, 1)
    );
    expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), -1)).toEqual(
      new Date(2016, DEC, 1)
    );
  });

  it('should respect month length differences when adding months', () => {
    expect(adapter.addCalendarMonths(new Date(2017, JAN, 31), 1)).toEqual(
      new Date(2017, FEB, 28)
    );
    expect(adapter.addCalendarMonths(new Date(2017, MAR, 31), -1)).toEqual(
      new Date(2017, FEB, 28)
    );
  });

  it('should add days', () => {
    expect(adapter.addCalendarDays(new Date(2017, JAN, 1), 1)).toEqual(
      new Date(2017, JAN, 2)
    );
    expect(adapter.addCalendarDays(new Date(2017, JAN, 1), -1)).toEqual(
      new Date(2016, DEC, 31)
    );
  });

  it('should clone', () => {
    const date = new Date(2017, JAN, 1);
    expect(adapter.clone(date)).toEqual(date);
    expect(adapter.clone(date)).not.toBe(date);
  });

  it('should preserve time when cloning', () => {
    const date = new Date(2017, JAN, 1, 4, 5, 6);
    expect(adapter.clone(date)).toEqual(date);
    expect(adapter.clone(date)).not.toBe(date);
  });

  it('should compare dates', () => {
    expect(
      adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 2))
    ).toBeLessThan(0);
    expect(
      adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, FEB, 1))
    ).toBeLessThan(0);
    expect(
      adapter.compareDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1))
    ).toBeLessThan(0);
    expect(
      adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 1))
    ).toBe(0);
    expect(
      adapter.compareDate(new Date(2018, JAN, 1), new Date(2017, JAN, 1))
    ).toBeGreaterThan(0);
    expect(
      adapter.compareDate(new Date(2017, FEB, 1), new Date(2017, JAN, 1))
    ).toBeGreaterThan(0);
    expect(
      adapter.compareDate(new Date(2017, JAN, 2), new Date(2017, JAN, 1))
    ).toBeGreaterThan(0);
  });

  it('should clamp date at lower bound', () => {
    expect(
      adapter.clampDate(
        new Date(2017, JAN, 1),
        new Date(2018, JAN, 1),
        new Date(2019, JAN, 1)
      )
    ).toEqual(new Date(2018, JAN, 1));
  });

  it('should clamp date at upper bound', () => {
    expect(
      adapter.clampDate(
        new Date(2020, JAN, 1),
        new Date(2018, JAN, 1),
        new Date(2019, JAN, 1)
      )
    ).toEqual(new Date(2019, JAN, 1));
  });

  it('should clamp date already within bounds', () => {
    expect(
      adapter.clampDate(
        new Date(2018, FEB, 1),
        new Date(2018, JAN, 1),
        new Date(2019, JAN, 1)
      )
    ).toEqual(new Date(2018, FEB, 1));
  });

  it('should use UTC for formatting by default', () => {
    expect(adapter.format(new Date(1800, 7, 14), 'E MMM dd yyyy')).toBe(
      'Thu Aug 14 1800'
    );
  });

  it('should count today as a valid date instance', () => {
    const d = new Date();
    expect(adapter.isValid(d)).toBe(true);
    expect(adapter.isDateInstance(d)).toBe(true);
  });

  it('should count an invalid date as an invalid date instance', () => {
    const d = new Date(NaN);
    expect(adapter.isValid(d)).toBe(false);
    expect(adapter.isDateInstance(d)).toBe(true);
  });

  it('should count a string as not a date instance', () => {
    const d = '1/1/2017';
    expect(adapter.isDateInstance(d)).toBe(false);
  });

  it('should create dates from valid ISO strings', () => {
    assertValidDate(adapter.deserialize('1985-04-12T23:20:50.52Z'), true);
    assertValidDate(adapter.deserialize('1996-12-19T16:39:57-08:00'), true);
    assertValidDate(adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true);
    assertValidDate(adapter.deserialize('2017-01-01'), true);
    assertValidDate(adapter.deserialize('2017-01-01T00:00:00'), true);
    assertValidDate(adapter.deserialize('1990-13-31T23:59:00Z'), false);
    assertValidDate(adapter.deserialize('1/1/2017'), false);
    assertValidDate(adapter.deserialize('2017-01-01T'), true);
    assertValidDate(adapter.deserialize(1483228800), true);
    expect(adapter.deserialize('')).toBeNull();
    expect(adapter.deserialize(null)).toBeNull();
    expect(adapter.deserialize([])).toBeNull();
    assertValidDate(adapter.deserialize(new Date()), true);
    assertValidDate(adapter.deserialize(new Date(NaN)), false);
    assertValidDate(adapter.deserialize(1483228800), true);
  });

  it('should format Date to ISO8601 string', () => {
    expect(adapter.toIso8601(new Date(2017, JAN, 1))).toEqual(
      new Date(2017, JAN, 1).toISOString()
    );
  });

  it('should create an invalid date', () => {
    assertValidDate(adapter.invalid(), false);
  });

  it('should not throw when attempting to format a date with a year less than 1', () => {
    expect(() => adapter.format(new Date(-1, 1, 1), 'd/d/yyyy')).not.toThrow();
  });

  it('should not throw when attempting to format a date with a year greater than 9999', () => {
    expect(() =>
      adapter.format(new Date(10000, 1, 1), 'd/d/yyyy')
    ).not.toThrow();
  });
});
Example #21
Source File: select.component.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('SelectComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let inputEl: HTMLInputElement;
  let ocEl: HTMLElement;
  let getLabelEl: () => HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SelectModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('.aui-select'));
    el = debugEl.nativeElement;
    inputEl = debugEl.query(By.css('input.aui-input'))
      .nativeElement as HTMLInputElement;
    getLabelEl = () => el.querySelector('.aui-select__label');

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should properties work correctly', () => {
    expect(inputEl.placeholder).toBe('');
    expect(inputEl.disabled).toBeFalsy();
    expect(inputEl.className).toContain('aui-input--medium');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Medium);
    });

    ins.disabled = true;
    ins.loading = true;
    ins.clearable = true;
    ins.size = ComponentSize.Large;
    fixture.detectChanges();

    expect(inputEl.disabled).toBeTruthy();
    expect(inputEl.className).toContain('aui-input--large');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Large);
    });
  });

  it('should [(value)] work', () => {
    el.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    const optionEls = ocEl.querySelectorAll('.aui-option');
    expect(optionEls.item(0).className).toContain('isSelected');
    expect(getLabelEl().innerHTML).toContain('1');
    ins.value = {
      label: '5',
      value: 5,
    };
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('5');

    ins.value = {
      label: '0',
      value: Symbol(0),
    };
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('0');

    optionEls.item(1).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value.value).toBe(2);
    expect(getLabelEl().innerHTML).toContain('2');
  });

  it('should clearable work', () => {
    ins.clearable = true;
    fixture.detectChanges();

    expect(ins.value.value).toBe(1);
    expect(getLabelEl().innerHTML).toContain('1');

    const closeEl = el.querySelector('.aui-select__clear');
    closeEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ins.value).toBe(null);
    expect(getLabelEl().textContent).toEqual('');
  });

  it('should label correctly rendered', () => {
    ins.getOptionLabel = (label: string) => `custom label for ${label}`;
    expect(getLabelEl().innerHTML).toContain('1');
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('custom label for 1');
    ins.getOptionLabel = (label: string) => `new custom label for ${label}`;
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('new custom label for 1');
  });
});
Example #22
Source File: login.interceptor.spec.ts    From sba-angular with MIT License 4 votes vote down vote up
describe("login interceptor", () => {
  let interceptorInstance: HttpInterceptor | null;
  let httpClient: HttpClient;
  let httpMock: HttpTestingController;

  function getInterceptorInstance<T extends HttpInterceptor>(interceptors: HttpInterceptor[], type: any): HttpInterceptor | null {
    let searchedInterceptor: HttpInterceptor | null = null;
    interceptors.forEach((interceptor: HttpInterceptor) => {
      if (interceptor instanceof type) {
        searchedInterceptor = interceptor;
      }
    });
    return searchedInterceptor;
  }

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        // ...
      ],
      providers: [
        {provide: START_CONFIG, useValue: {app: "testing_app"}},
        {provide: HTTP_REQUEST_INITIALIZERS, useValue: {}},
        {provide: LoginService, deps: [START_CONFIG], useClass: LoginService},
        {provide: AuthenticationService, deps: [START_CONFIG], useClass: AuthenticationService},
        {provide: HTTP_INTERCEPTORS, deps: [START_CONFIG, HTTP_REQUEST_INITIALIZERS, NotificationsService, LoginService, AuthenticationService], useClass: LoginInterceptor, multi: true}
      ]
    });

    // get interceptor instance
    interceptorInstance = getInterceptorInstance<LoginInterceptor>(TestBed.inject(HTTP_INTERCEPTORS), LoginInterceptor);

    httpClient = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it("should retrieve interceptors list", inject(
    [HTTP_INTERCEPTORS, START_CONFIG, LoginService, AuthenticationService],
    (interceptors: typeof HTTP_INTERCEPTORS) => {
      (interceptors as any).forEach((interceptor: HttpInterceptor) => {
        if (interceptor instanceof LoginInterceptor) {
          expect(interceptor).toBeDefined();
        }
      });
    }
  ));

  it("should instanciate interceptor", () => {
    expect(interceptorInstance).toBeDefined();
  })


  it('When 401, try to get Credentials or error is rethrow', () => {
    const login = TestBed.inject(LoginService);
    spyOn(login, "getCredentials").and.returnValue(Promise.resolve());
    // before refacto this method doesn't exists
    spyOn<any>(interceptorInstance, "handle401Error").and.callThrough();

    const message = '401 error';

    // Make an HTTP GET request
    httpClient.get("/data").subscribe(
      res => fail('should have failed with the 401 error'),
      (err: HttpErrorResponse) => {
        expect(err.error).toEqual(message, 'message');
      }
    );

    // The following `expectOne()` will match the request's URL.
    const req = httpMock.expectOne("/data");

    // Respond with mock error
    req.flush(message, {status: 401, statusText: 'Unauthorized'});

    expect(login.getCredentials).toHaveBeenCalledTimes(1);
    expect((interceptorInstance as LoginInterceptor)["handle401Error"]).toHaveBeenCalledTimes(1);
  });

  it('When an error occurs, error is rethrow', () => {
    const login = TestBed.inject(LoginService);
    spyOn(login, "getCredentials").and.returnValue(Promise.resolve());
    // before refacto this method doesn't exists
    spyOn<any>(interceptorInstance, "handle401Error").and.callThrough();

    const message = '403 Forbidden';

    // Make an HTTP GET request
    httpClient.get("/data").subscribe(
      res => fail('should have failed with the 403 error'),
      (err: HttpErrorResponse) => {
        expect(err.error).toEqual(message, 'message');
      }
    );

    // The following `expectOne()` will match the request's URL.
    const req = httpMock.expectOne("/data");

    // Respond with mock error
    req.flush(message, {status: 403, statusText: 'Forbidden'});

    expect(login.getCredentials).not.toHaveBeenCalled();
  });

  it("should intercept request", () => {
    httpClient.get("/data").subscribe(res => {
      expect(res).toEqual("ok");
    });

    const req = httpMock.expectOne("/data");
    req.flush("ok");

    expect(req.request.params.has("noAutoAuthentication")).toBeFalse();
    expect(req.request.params.has("noUserOverride")).toBeFalse();
    expect(req.request.params.has("noNotify")).toBeFalse();

    expect(req.request.headers.has("sinequa-force-camel-case")).toBeTrue();
  });

  it("should no intercept request with 'noIntercept' params", () => {
    // noIntercept
    const params = new HttpParams().set("noIntercept", "noIntercept")

    httpClient.get("/data", {params}).subscribe(res => {
      expect(res).toEqual("ok");
    });

    const req = httpMock.expectOne("/data?noIntercept=noIntercept");
    req.flush("ok");

  });

});
Example #23
Source File: tooltip.directive.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('TooltipDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let hostEl: HTMLElement;
  let ocEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TooltipModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('#host'));
    hostEl = debugEl.nativeElement;

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should render tooltip when mouseenter & destroy tooltip when mouseleave', fakeAsync(() => {
    hostEl.dispatchEvent(new Event('mouseenter'));
    tick(DISPLAY_DELAY);
    fixture.detectChanges();

    expect(ins.tooltip.isCreated).toBeTruthy();
    expect(ocEl.querySelector('.aui-tooltip').innerHTML).toContain(
      'hello world',
    );
    expect(hostEl.className).toContain('tooltip-actived');

    hostEl.dispatchEvent(new Event('mouseleave'));
    tick(HIDDEN_DELAY);

    expect(ins.tooltip.isCreated).toBeFalsy();
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
    expect(hostEl.className).not.toContain('tooltip-actived');
  }));

  it('should still display when mouse move to tooltip', fakeAsync(() => {
    hostEl.dispatchEvent(new Event('mouseenter'));
    tick(DISPLAY_DELAY);
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('mouseleave'));
    tick(20);
    ocEl.querySelector('.aui-tooltip').dispatchEvent(new Event('mouseenter'));
    tick(20);
    fixture.detectChanges();

    expect(ins.tooltip.isCreated).toBeTruthy();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    tick(HIDDEN_DELAY - 40);
  }));

  it('should click trigger work', () => {
    ins.trigger = TooltipTrigger.Click;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    document.body.click();
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();

    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    hostEl.dispatchEvent(new Event('click'));
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should focus trigger work', () => {
    ins.trigger = TooltipTrigger.Focus;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('focus'));
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();

    hostEl.dispatchEvent(new Event('blur'));

    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should can be disabled', () => {
    ins.disabled = true;
    ins.trigger = TooltipTrigger.Click;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should tooltip configs work', () => {
    ins.trigger = TooltipTrigger.Click;
    ins.content = 'custom content';
    ins.type = TooltipType.Primary;
    ins.position = 'start';
    ins.className = 'custom-class';
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    const tooltipEl = ocEl.querySelector('.aui-tooltip');
    expect(tooltipEl.innerHTML).toContain('custom content');
    expect(tooltipEl.className).toContain('aui-tooltip--primary');
    expect(tooltipEl.className).toContain('aui-tooltip--start');
    expect(tooltipEl.className).toContain('custom-class');
  });

  it('should tooltip render templateRef', () => {
    ins.trigger = TooltipTrigger.Click;
    ins.content = ins.templateRef;
    ins.context = { text: 'custom context' };
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ocEl.querySelector('#dataNode').innerHTML).toContain(
      'custom context',
    );
  });

  it('should emit show event', () =>
    new Promise(resolve => {
      ins.tooltip.show.subscribe(resolve);

      ins.trigger = TooltipTrigger.Click;
      fixture.detectChanges();
      hostEl.dispatchEvent(new Event('click'));
      fixture.detectChanges();
    }));

  it('should emit hide event', () =>
    new Promise(resolve => {
      ins.tooltip.hide.subscribe(resolve);

      ins.trigger = TooltipTrigger.Click;
      fixture.detectChanges();
      hostEl.dispatchEvent(new Event('click'));
      document.body.click();
    }));
});
Example #24
Source File: data-view-map.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 4 votes vote down vote up
describe('DataViewMapComponent', () => {
  let component: DataViewMapComponent
  let fixture: ComponentFixture<DataViewMapComponent>
  let mdViewFacade

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        DataViewMapComponent,
        MockMapContextComponent,
        MockDropdownSelectorComponent,
        MockExternalViewerButtonComponent,
        MockLoadingMaskComponent,
        MockPopupAlertComponent,
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        {
          provide: MdViewFacade,
          useClass: MdViewFacadeMock,
        },
        {
          provide: MapUtilsService,
          useClass: MapUtilsServiceMock,
        },
        {
          provide: DataService,
          useClass: DataServiceMock,
        },
        {
          provide: MapStyleService,
          useValue: mapStyleServiceMock,
        },
        {
          provide: MapManagerService,
          useValue: mapManagerMock,
        },
        {
          provide: FeatureInfoService,
          useValue: featureInfoServiceMock,
        },
      ],
      imports: [TranslateModule.forRoot()],
    }).compileComponents()
    mdViewFacade = TestBed.inject(MdViewFacade)
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(DataViewMapComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

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

  describe('map layers', () => {
    let mapComponent: MockMapContextComponent
    let dropdownComponent: DropdownSelectorComponent
    let externalViewerButtonComponent: MockExternalViewerButtonComponent

    beforeEach(() => {
      mapComponent = fixture.debugElement.query(
        By.directive(MockMapContextComponent)
      ).componentInstance
      dropdownComponent = fixture.debugElement.query(
        By.directive(MockDropdownSelectorComponent)
      ).componentInstance
      externalViewerButtonComponent = fixture.debugElement.query(
        By.directive(MockExternalViewerButtonComponent)
      ).componentInstance
    })

    describe('with no link compatible with MAP_API or GEODATA usage', () => {
      beforeEach(() => {
        mdViewFacade.mapApiLinks$.next([])
        mdViewFacade.geoDataLinks$.next([])
        fixture.detectChanges()
      })
      it('emits a map context with no layer', () => {
        expect(mapComponent.context).toEqual({
          layers: [],
          view: expect.any(Object),
        })
      })
      it('emits map config to map component', () => {
        expect(mapComponent.mapConfig).toEqual(mapConfigMock)
      })
      it('emits map config to external viewer component', () => {
        expect(externalViewerButtonComponent.mapConfig).toEqual(mapConfigMock)
      })
      it('emits no link to external viewer component', () => {
        expect(externalViewerButtonComponent.link).toEqual(undefined)
      })
      it('provides a placeholder value to the dropdown', () => {
        expect(dropdownComponent.choices).toEqual([
          {
            value: 0,
            label: expect.any(String),
          },
        ])
      })
    })

    describe('with several links compatible with MAP_API usage', () => {
      beforeEach(() => {
        mdViewFacade.mapApiLinks$.next([
          {
            url: 'http://abcd.com/',
            name: 'layer1',
            label: 'layer1',
            protocol: 'OGC:WMS--1-3-0',
          },
          {
            url: 'http://abcd.com/',
            name: 'layer2',
            label: 'layer2',
            protocol: 'OGC:WMS--1-1-0',
          },
        ])
        mdViewFacade.geoDataLinks$.next([])
        fixture.detectChanges()
      })
      it('emits a map context with the first compatible link', () => {
        expect(mapComponent.context).toEqual({
          layers: [
            {
              url: 'http://abcd.com/',
              name: 'layer1',
              type: 'wms',
            },
          ],
          view: expect.any(Object),
        })
      })
      it('provides a list of links to the dropdown', () => {
        expect(dropdownComponent.choices).toEqual([
          {
            value: 0,
            label: 'layer1 (WMS)',
          },
          {
            value: 1,
            label: 'layer2 (WMS)',
          },
        ])
      })
      it('provides first (selected) link to the external viewer component', () => {
        expect(externalViewerButtonComponent.link).toEqual({
          url: 'http://abcd.com/',
          label: 'layer1',
          name: 'layer1',
          protocol: 'OGC:WMS--1-3-0',
        })
      })
    })

    describe('with links compatible with MAP_API and GEODATA usage', () => {
      beforeEach(() => {
        mdViewFacade.mapApiLinks$.next([
          {
            url: 'http://abcd.com/',
            name: 'layer1',
            label: 'layer1',
            protocol: 'OGC:WMS',
          },
        ])
        mdViewFacade.geoDataLinks$.next([
          {
            url: 'http://abcd.com/wfs',
            name: 'featuretype',
            label: 'featuretype',
            protocol: 'OGC:WFS--2-0-0',
          },
          {
            url: 'http://abcd.com/data.geojson',
            name: 'data.geojson',
            label: 'data.geojson',
            protocol: 'WWW:DOWNLOAD',
            format: 'geojson',
          },
        ])
        fixture.detectChanges()
      })
      it('provides a list of links to the dropdown', () => {
        expect(dropdownComponent.choices).toEqual([
          {
            value: 0,
            label: 'layer1 (WMS)',
          },
          {
            value: 1,
            label: 'featuretype (WFS)',
          },
          {
            value: 2,
            label: 'data.geojson (geojson)',
          },
        ])
      })
      it('provides first (selected) link to the external viewer component', () => {
        expect(externalViewerButtonComponent.link).toEqual({
          url: 'http://abcd.com/',
          name: 'layer1',
          label: 'layer1',
          protocol: 'OGC:WMS',
        })
      })
    })

    describe('with a link using WFS protocol', () => {
      beforeEach(fakeAsync(() => {
        mdViewFacade.mapApiLinks$.next([])
        mdViewFacade.geoDataLinks$.next([
          {
            url: 'http://abcd.com/wfs',
            name: 'featuretype',
            protocol: 'OGC:WFS',
          },
        ])
        tick(200)
        fixture.detectChanges()
      }))
      it('emits a map context with the downloaded data from WFS', () => {
        expect(mapComponent.context).toEqual({
          layers: [
            {
              type: 'geojson',
              data: SAMPLE_GEOJSON,
            },
          ],
          view: expect.any(Object),
        })
      })
    })

    describe('with a link using ESRI:REST protocol', () => {
      beforeEach(fakeAsync(() => {
        mdViewFacade.mapApiLinks$.next([])
        mdViewFacade.geoDataLinks$.next([
          {
            protocol: 'ESRI:REST',
            name: 'mes_hdf',
            url: 'https://services8.arcgis.com/rxZzohbySMKHTNcy/arcgis/rest/services/mes_hdf/WFSServer/0',
          },
        ])
        tick(200)
        fixture.detectChanges()
      }))
      it('emits a map context with the the downloaded data from WFS', () => {
        expect(mapComponent.context).toEqual({
          layers: [
            {
              type: 'geojson',
              data: SAMPLE_GEOJSON,
            },
          ],
          view: expect.any(Object),
        })
      })
    })

    describe('with a link using WFS which returns an error', () => {
      beforeEach(() => {
        mdViewFacade.mapApiLinks$.next([])
        mdViewFacade.geoDataLinks$.next([
          {
            url: 'http://abcd.com/wfs/error',
            name: 'featuretype',
            protocol: 'OGC:WFS',
          },
        ])
      })
      it('shows an error', () => {
        expect(component.error).toEqual('data loading error')
      })
    })

    describe('with a link using DOWNLOAD protocol', () => {
      describe('during download', () => {
        beforeEach(fakeAsync(() => {
          mdViewFacade.mapApiLinks$.next([])
          mdViewFacade.geoDataLinks$.next([
            {
              url: 'http://abcd.com/data.geojson',
              name: 'data.geojson',
              protocol: 'WWW:DOWNLOAD--https',
              format: 'geojson',
            },
          ])
          fixture.detectChanges()
          tick(50)
          discardPeriodicTasks()
        }))
        it('does not emit immediately a map context', () => {
          expect(mapComponent.context).toBe(null)
        })
        it('shows a loading indicator', () => {
          expect(
            fixture.debugElement.query(By.directive(MockLoadingMaskComponent))
          ).toBeTruthy()
        })
      })
      describe('after download', () => {
        beforeEach(fakeAsync(() => {
          mdViewFacade.mapApiLinks$.next([])
          mdViewFacade.geoDataLinks$.next([
            {
              url: 'http://abcd.com/data.geojson',
              name: 'data.geojson',
              protocol: 'WWW:DOWNLOAD--https',
              format: 'geojson',
            },
          ])
          fixture.detectChanges()
          tick(200)
        }))
        it('emits a map context after loading with the downloaded data', () => {
          fixture.detectChanges()
          expect(mapComponent.context).toEqual({
            layers: [
              {
                type: 'geojson',
                data: SAMPLE_GEOJSON,
              },
            ],
            view: expect.any(Object),
          })
        })
        it('does not show a loading indicator', () => {
          fixture.detectChanges()
          expect(
            fixture.debugElement.query(By.directive(MockLoadingMaskComponent))
          ).toBeFalsy()
        })
      })
    })

    describe('when receiving several metadata records', () => {
      beforeEach(() => {
        mdViewFacade.mapApiLinks$.next([])
        mdViewFacade.geoDataLinks$.next([
          {
            url: 'http://abcd.com/data.geojson',
            name: 'data.geojson',
            label: 'data.geojson',
            protocol: 'WWW:DOWNLOAD',
            format: 'geojson',
          },
        ])
        mdViewFacade.mapApiLinks$.next([
          {
            url: 'http://abcd.com/',
            name: 'layer',
            label: 'layer',
            protocol: 'OGC:WMS',
          },
        ])
        mdViewFacade.geoDataLinks$.next([])
        fixture.detectChanges()
      })
      it('emits a map context with the link from the last record', () => {
        expect(mapComponent.context).toEqual({
          layers: [
            {
              url: 'http://abcd.com/',
              name: 'layer',
              type: 'wms',
            },
          ],
          view: expect.any(Object),
        })
      })
      it('provides a list of links to the dropdown', () => {
        expect(dropdownComponent.choices).toEqual([
          {
            value: 0,
            label: 'layer (WMS)',
          },
        ])
      })
      it('provides first (selected) link to the external viewer component', () => {
        expect(externalViewerButtonComponent.link).toEqual({
          url: 'http://abcd.com/',
          name: 'layer',
          label: 'layer',
          protocol: 'OGC:WMS',
        })
      })
    })

    describe('when selecting a layer', () => {
      beforeEach(inject([MapUtilsService], (mapUtils) => {
        mapUtils._returnImmediately = false
        mdViewFacade.mapApiLinks$.next([
          {
            url: 'http://abcd.com/',
            name: 'layer1',
            protocol: 'OGC:WMS',
          },
          {
            url: 'http://abcd.com/',
            name: 'layer2',
            protocol: 'OGC:WMS',
          },
        ])
        mdViewFacade.geoDataLinks$.next([])
        dropdownComponent.selectValue.emit(1)
        fixture.detectChanges()
      }))
      describe('while extent is not ready', () => {
        it('does not emit a map context', () => {
          expect(mapComponent.context).toBeFalsy()
        })
      })
      describe('when extent is received', () => {
        beforeEach(inject([MapUtilsService], (mapUtils) => {
          mapUtils._observer.next([-100, -200, 100, 200])
          fixture.detectChanges()
        }))
        it('emits a new map context with the selected layer and the computed extent', () => {
          expect(mapComponent.context).toEqual({
            layers: [
              {
                url: 'http://abcd.com/',
                name: 'layer2',
                type: 'wms',
              },
            ],
            view: {
              extent: [-100, -200, 100, 200],
            },
          })
        })
        it('provides selected link to the external viewer component', () => {
          expect(externalViewerButtonComponent.link).toEqual({
            url: 'http://abcd.com/',
            name: 'layer2',
            protocol: 'OGC:WMS',
          })
        })
      })
      describe('when extent computation fails', () => {
        beforeEach(inject([MapUtilsService], (mapUtils) => {
          mapUtils._observer.error('extent computation failed')
          fixture.detectChanges()
        }))
        it('emits a new map context with the selected layer and a default view', () => {
          expect(mapComponent.context).toEqual({
            layers: [
              {
                url: 'http://abcd.com/',
                name: 'layer2',
                type: 'wms',
              },
            ],
            view: expect.any(Object),
          })
        })
        it('provides selected link to the external viewer component', () => {
          expect(externalViewerButtonComponent.link).toEqual({
            url: 'http://abcd.com/',
            name: 'layer2',
            protocol: 'OGC:WMS',
          })
        })
      })
      describe('selecting another layer, while extent is not ready', () => {
        beforeEach(inject([MapUtilsService], (mapUtils) => {
          mapUtils._observer.next([-10, -20, 10, 20])
          dropdownComponent.selectValue.emit(0)
          fixture.detectChanges()
        }))
        it('does not emit another map context', () => {
          expect(mapComponent.context.layers).toEqual([
            {
              url: 'http://abcd.com/',
              name: 'layer2',
              type: 'wms',
            },
          ])
        })
      })
    })
  })

  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: new GeoJSON().readFeatures(
        FEATURE_COLLECTION_POINT_FIXTURE_4326,
        {
          featureProjection: 'EPSG:3857',
          dataProjection: 'EPSG:4326',
        }
      ),
    }),
  })
  const selectionFeatures = [
    vectorLayer
      .getSource()
      .getFeatures()
      .find((feature) => feature.getId() === 2),
  ]

  describe('feature info', () => {
    it('creates selection style', () => {
      expect(component['selectionStyle']).toBeTruthy()
    })
    describe('#onMapFeatureSelect', () => {
      beforeEach(() => {
        const changeDetectorRef =
          fixture.debugElement.injector.get(ChangeDetectorRef)
        jest.spyOn(changeDetectorRef.constructor.prototype, 'detectChanges')
        jest.spyOn(component, 'resetSelection')
        featureInfoServiceMock.features$.next(selectionFeatures)
      })
      it('reset the selection first', () => {
        expect(component.resetSelection).toHaveBeenCalled()
      })
      it('set the selection', () => {
        expect(component.selection).toBe(selectionFeatures[0])
      })
      it('change detection applied', () => {
        expect(component['changeRef'].detectChanges).toHaveBeenCalled()
      })
      it('set feature style', () => {
        expect(component.selection.getStyle()).toBe(component['selectionStyle'])
      })
    })
    describe('#resetSelection', () => {
      beforeEach(() => {
        component.selection = selectionFeatures[0]
        component.resetSelection()
      })
      it('reset the style of the feature', () => {
        expect(selectionFeatures[0].getStyle()).toBeNull()
      })
      it('remove the selection', () => {
        expect(component.selection).toBeFalsy()
      })
    })
    describe('changing the map context', () => {
      beforeEach(() => {
        jest.spyOn(component, 'resetSelection')
        mdViewFacade.geoDataLinks$.next([])
        mdViewFacade.mapApiLinks$.next([])
      })
      it('resets selection', () => {
        expect(component.resetSelection).toHaveBeenCalled()
      })
    })
  })
})
Example #25
Source File: app.component.spec.ts    From mysteryofthreebots with Apache License 2.0 4 votes vote down vote up
describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      declarations: [
        AppComponent,
        DialogHostComponent,
        HomeComponent,
        NavButtonsComponent,
        ChatComponent,
        InterviewPaneComponent,
        DialogCloseButtonComponent,
        HelpDialogComponent,
        HowDialogComponent,
        NotesDialogComponent,
        MapDialogComponent,
        SolveDialogComponent,
        WinDialogComponent,
        IncompleteSolutionDialogComponent,
        IncorrectSolutionDialogComponent,
        WelcomeDialogComponent,
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
      ],
    }).overrideModule(
      BrowserDynamicTestingModule,
      {
        set: {
          entryComponents: [
            HelpDialogComponent,
            HowDialogComponent,
            NotesDialogComponent,
            MapDialogComponent,
            SolveDialogComponent,
            WinDialogComponent,
            IncompleteSolutionDialogComponent,
            IncorrectSolutionDialogComponent,
            WelcomeDialogComponent,
          ],
        },
      }
    ).compileComponents();
  }));

  afterEach(() => {
    fixture.debugElement.nativeElement.remove();
    fixture.destroy();
  });

  it('should create the app', () => {
    fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'The Mystery of the Three Bots'`, () => {
    fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('The Mystery of the Three Bots');
  });

  it('should load the models', inject([BotResponseService], (responseService: BotResponseService) => {
    spyOn(responseService, 'loadModels').and.callThrough();
    fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    expect(responseService.loadModels).toHaveBeenCalled();
  }));

  it('should initialize state', inject([BotResponseService], (responseService: BotResponseService) => {
    spyOn(responseService, 'setState').and.callThrough();
    fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    expect(responseService.setState).toHaveBeenCalledWith({
      chef: 'initial',
    });
  }));
});
Example #26
Source File: multi-select.component.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('multiSelectComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let ocEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SelectModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('.aui-multi-select'));
    el = debugEl.nativeElement;
    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should properties work correctly', fakeAsync(() => {
    expect(
      el.querySelector('.aui-multi-select__placeholder').innerHTML.trim(),
    ).toBe('');
    expect(el.className).not.toContain('isDisabled');
    expect(el.className).toContain('aui-multi-select--medium');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Medium);
    });
    ins.disabled = true;
    ins.loading = true;
    ins.clearable = true;
    ins.value = [1, 2];
    ins.size = ComponentSize.Large;
    ins.placeholder = 'placeholder';
    fixture.detectChanges();
    tick();
    expect(
      el.querySelector('.aui-multi-select__placeholder').innerHTML,
    ).toContain('placeholder');
    expect(el.className).toContain('isDisabled');
    expect(el.className).toContain('aui-multi-select--large');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Large);
    });
  }));

  it('should ngModel work', fakeAsync(() => {
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(2);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(2);
    el.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    ocEl
      .querySelectorAll('.aui-option')
      .item(2)
      .dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value).toEqual([1, 2, 3]);
  }));

  it('should clearable work', fakeAsync(() => {
    ins.clearable = true;
    fixture.detectChanges();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(2);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(2);
    const closeEl = el.querySelector('.aui-multi-select__clear');
    closeEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    expect(ins.value).toEqual([]);
  }));

  it('should tagClassFn work', fakeAsync(() => {
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll('.tag-1').length).toBe(1);
    expect(el.querySelectorAll('.tag-2').length).toBe(1);
  }));
});
Example #27
Source File: show.component.spec.ts    From litefy with MIT License 4 votes vote down vote up
describe('ShowComponent', () => {
  let component: ShowComponent;
  let fixture: ComponentFixture<ShowComponent>;
  let showService;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ShowComponent],
      imports: [AppModule]
    })
      .compileComponents();
  }));

  beforeEach(inject([SpotifyShowService], s => {
    showService = s;
    fixture = TestBed.createComponent(ShowComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

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

  it('should get all info from artist', () => {
    const responseShow: SpotifyApi.ShowObjectSimplified = {
      "available_markets": ["AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA"],
      "copyrights": [],
      "description": "Candid conversations with entrepreneurs, artists, athletes, visionaries of all kinds—about their successes, and their failures, and what they learned from both. Hosted by Alex Blumberg, from Gimlet Media.",
      "explicit": true,
      "external_urls": {
        "spotify": "https://open.spotify.com/show/5CfCWKI5pZ28U0uOzXkDHe"
      },
      "href": "https://api.spotify.com/v1/shows/5CfCWKI5pZ28U0uOzXkDHe",
      "id": "5CfCWKI5pZ28U0uOzXkDHe",
      "images": [{
        "height": 640,
        "url": "https://i.scdn.co/image/12903409b9e5dd26f2a41e401cd7fcabd5164ed4",
        "width": 640
      }, {
        "height": 300,
        "url": "https://i.scdn.co/image/4f19eb7986a7c2246d713dcc46684e2187ccea4f",
        "width": 300
      }, {
        "height": 64,
        "url": "https://i.scdn.co/image/c0b072976a28792a4b451dfc7011a2176ec8cd34",
        "width": 64
      }],
      "is_externally_hosted": false,
      "languages": ["en"],
      "media_type": "audio",
      "name": "Without Fail",
      "publisher": "Gimlet",
      "type": "show",
      "uri": "spotify:show:5CfCWKI5pZ28U0uOzXkDHe"
    };
    const responseEpisodes = {
      "episodes" : [ {
    "audio_preview_url" : "https://p.scdn.co/mp3-preview/7e8f7a00f1425d495bcb992bae48a19c31342490",
    "description" : "Följ med till Riddarhuset och hör om dråpliga motiv och billiga lösningar på husets drygt 2 300 vapensköldar som nu studerats. Och hör hur stormakten Sveriges krig finansierades av Frankrike.  Skelögda ugglor och halshuggna troll är några av motiven på de drygt 2&nbsp;300 vapensköldar som hänger i Riddarhuset i Stockholm. Den svenska adelns grafiska profiler har nu hamnat under luppen när heraldikern Magnus Bäckmark som förste forskare skärskådat detta bortglömda kulturarvs estetik och historia. Vetenskapsradion Historia följer med honom till Riddarhuset för att fascineras av både vackra och tokfula motiv. Dessutom om att den svenska stormaktstiden nu måste omvärderas efter att historikern Svante Norrhem undersökt de enorma summor som Sverige erhöll av Frankrike. Under närmare 170 år var Sverige närmast en klientstat till Frankrike, där närmare 20 procent av svensk ekonomi bestod av franska subsidier. Tobias Svanelid undersöker hur förhållandet påverkade länderna och hur mycket av den svenska stormaktstiden som egentligen var fransk.",
    "duration_ms" : 2685023,
    "explicit" : false,
    "external_urls" : {
      "spotify" : "https://open.spotify.com/episode/77o6BIVlYM3msb4MMIL1jH"
    },
    "href" : "https://api.spotify.com/v1/episodes/77o6BIVlYM3msb4MMIL1jH",
    "id" : "77o6BIVlYM3msb4MMIL1jH",
    "images" : [ {
      "height" : 640,
      "url" : "https://i.scdn.co/image/8092469858486ff19eeefcea7ec5c17b72c9590a",
      "width" : 640
    }, {
      "height" : 300,
      "url" : "https://i.scdn.co/image/7e921e844f4deb5a8fbdacba7abb6210357237e5",
      "width" : 300
    }, {
      "height" : 64,
      "url" : "https://i.scdn.co/image/729df823ef7f9a6f8aaf57d532490c9aab43e0dc",
      "width" : 64
    } ],
    "is_externally_hosted" : false,
    "is_playable" : true,
    "language" : "sv",
    "name" : "Riddarnas vapensköldar under lupp",
    "release_date" : "2019-09-10",
    "release_date_precision" : "day",
    "show" : {
      "available_markets" : [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ],
      "copyrights" : [ ],
      "description" : "Vi är där historien är. Ansvarig utgivare: Nina Glans",
      "explicit" : false,
      "external_urls" : {
        "spotify" : "https://open.spotify.com/show/38bS44xjbVVZ3No3ByF1dJ"
      },
      "href" : "https://api.spotify.com/v1/shows/38bS44xjbVVZ3No3ByF1dJ",
      "id" : "38bS44xjbVVZ3No3ByF1dJ",
      "images" : [ {
        "height" : 640,
        "url" : "https://i.scdn.co/image/3c59a8b611000c8b10c8013013c3783dfb87a3bc",
        "width" : 640
      }, {
        "height" : 300,
        "url" : "https://i.scdn.co/image/2d70c06ac70d8c6144c94cabf7f4abcf85c4b7e4",
        "width" : 300
      }, {
        "height" : 64,
        "url" : "https://i.scdn.co/image/3dc007829bc0663c24089e46743a9f4ae15e65f8",
        "width" : 64
      } ],
      "is_externally_hosted" : false,
      "languages" : [ "sv" ],
      "media_type" : "audio",
      "name" : "Vetenskapsradion Historia",
      "publisher" : "Sveriges Radio",
      "type" : "show",
      "uri" : "spotify:show:38bS44xjbVVZ3No3ByF1dJ"
    },
    "type" : "episode",
    "uri" : "spotify:episode:77o6BIVlYM3msb4MMIL1jH"
  }, {
    "audio_preview_url" : "https://p.scdn.co/mp3-preview/83bc7f2d40e850582a4ca118b33c256358de06ff",
    "description" : "Följ med Tobias Svanelid till Sveriges äldsta tegelkyrka, till Edsleskog mitt i den dalsländska granskogen, där ett religiöst skrytbygge skulle resas över ett skändligt brott.  I Edsleskog i Dalsland gräver arkeologerna nu ut vad som en gång verkar ha varit en av Sveriges största medeltidskyrkor, och kanske också den äldsta som byggts i tegel, 1200-talets high-tech-material. Tobias Svanelid reser dit för att höra historien om den märkliga och bortglömda kyrkan som grundlades på platsen för ett prästmord och dessutom kan ha varit Skarabiskopens försök att lägga beslag på det vilda Dalsland. Dessutom om sjudagarsveckan  idag ett välkänt koncept runt hela världen, men hur gammal är egentligen veckans historia? Dick Harrison vet svaret.",
    "duration_ms" : 2685023,
    "explicit" : false,
    "external_urls" : {
      "spotify" : "https://open.spotify.com/episode/0Q86acNRm6V9GYx55SXKwf"
    },
    "href" : "https://api.spotify.com/v1/episodes/0Q86acNRm6V9GYx55SXKwf",
    "id" : "0Q86acNRm6V9GYx55SXKwf",
    "images" : [ {
      "height" : 640,
      "url" : "https://i.scdn.co/image/b2398424d6158a21fe8677e2de5f6f3d1dc4a04f",
      "width" : 640
    }, {
      "height" : 300,
      "url" : "https://i.scdn.co/image/a52780a1d7e1bc42619413c3dea7042396c87f49",
      "width" : 300
    }, {
      "height" : 64,
      "url" : "https://i.scdn.co/image/88e21be860cf11f0b95ee8dfb47ddb08a13319a7",
      "width" : 64
    } ],
    "is_externally_hosted" : false,
    "is_playable" : true,
    "language" : "sv",
    "name" : "Okända katedralen i Dalsland",
    "release_date" : "2019-09-03",
    "release_date_precision" : "day",
    "show" : {
      "available_markets" : [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ],
      "copyrights" : [ ],
      "description" : "Vi är där historien är. Ansvarig utgivare: Nina Glans",
      "explicit" : false,
      "external_urls" : {
        "spotify" : "https://open.spotify.com/show/38bS44xjbVVZ3No3ByF1dJ"
      },
      "href" : "https://api.spotify.com/v1/shows/38bS44xjbVVZ3No3ByF1dJ",
      "id" : "38bS44xjbVVZ3No3ByF1dJ",
      "images" : [ {
        "height" : 640,
        "url" : "https://i.scdn.co/image/3c59a8b611000c8b10c8013013c3783dfb87a3bc",
        "width" : 640
      }, {
        "height" : 300,
        "url" : "https://i.scdn.co/image/2d70c06ac70d8c6144c94cabf7f4abcf85c4b7e4",
        "width" : 300
      }, {
        "height" : 64,
        "url" : "https://i.scdn.co/image/3dc007829bc0663c24089e46743a9f4ae15e65f8",
        "width" : 64
      } ],
      "is_externally_hosted" : false,
      "languages" : [ "sv" ],
      "media_type" : "audio",
      "name" : "Vetenskapsradion Historia",
      "publisher" : "Sveriges Radio",
      "type" : "show",
      "uri" : "spotify:show:38bS44xjbVVZ3No3ByF1dJ"
    },
    "type" : "episode",
    "uri" : "spotify:episode:0Q86acNRm6V9GYx55SXKwf"
  } ]
    };

    spyOn(showService, 'getArtist').and.returnValue(of(responseShow));
    spyOn(showService, 'getArtistTopTracks').and.returnValue(of(responseEpisodes));

    component.getAllInfoFromArtist();

    fixture.detectChanges();
    expect(component.show).toEqual(responseShow);
  });
});
Example #28
Source File: nav-buttons.component.spec.ts    From mysteryofthreebots with Apache License 2.0 4 votes vote down vote up
describe('NavButtonsComponent', () => {
  let component: NavButtonsComponent;
  let fixture: ComponentFixture<NavButtonsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ NavButtonsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NavButtonsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should open notes dialog on clicking Police Notes button', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'open');
      const navButton = (
        Array.from(
          fixture.debugElement.nativeElement.querySelectorAll('.button')
        ) as HTMLButtonElement[]
      ).find((button: HTMLButtonElement) => {
          return button.innerText === 'Police Notes';
        });
      navButton.click();
      expect(dialogService.open).toHaveBeenCalledWith(NotesDialogComponent);
    }
  ));

  it('should open map dialog on clicking Map button', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'open');
      const navButton = (
        Array.from(
          fixture.debugElement.nativeElement.querySelectorAll('.button')
        ) as HTMLButtonElement[]
      ).find((button: HTMLButtonElement) => {
          return button.innerText === 'Map';
        });
      navButton.click();
      expect(dialogService.open).toHaveBeenCalledWith(MapDialogComponent);
    }
  ));

  it('should open solve dialog on clicking Solve button', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'open');
      const navButton = (
        Array.from(
          fixture.debugElement.nativeElement.querySelectorAll('.button')
        ) as HTMLButtonElement[]
      ).find((button: HTMLButtonElement) => {
          return button.innerText === 'Solve';
        });
      navButton.click();
      expect(dialogService.open).toHaveBeenCalledWith(SolveDialogComponent);
    }
  ));

  it('should open help dialog on clicking Help button', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'open');
      const navButton = (
        Array.from(
          fixture.debugElement.nativeElement.querySelectorAll('.button')
        ) as HTMLButtonElement[]
      ).find((button: HTMLButtonElement) => {
          return button.innerText === 'Help';
        });
      navButton.click();
      expect(dialogService.open).toHaveBeenCalledWith(HelpDialogComponent);
    }
  ));

  it('should open how dialog on clicking How? button', inject(
    [DialogService],
    (dialogService: DialogService) => {
      spyOn(dialogService, 'open');
      const navButton = (
        Array.from(
          fixture.debugElement.nativeElement.querySelectorAll('.button')
        ) as HTMLButtonElement[]
      ).find((button: HTMLButtonElement) => {
          return button.innerText === 'How?';
        });
      navButton.click();
      expect(dialogService.open).toHaveBeenCalledWith(HowDialogComponent);
    }
  ));
});
Example #29
Source File: notification.service.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('NotificationService', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  let notificationService: NotificationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TestModule],
      providers: [
        {
          provide: NOTIFICATION_CONFIG,
          useValue: {
            duration: 3000,
            maxStack: 3,
          },
        },
      ],
    });

    fixture = TestBed.createComponent(TestComponent);

    inject(
      [OverlayContainer, NotificationService],
      (overlayContainer: OverlayContainer, service: NotificationService) => {
        ocEl = overlayContainer.getContainerElement();
        notificationService = service;
      },
    )();
  });

  it('should work with global config', () => {
    notificationService.success('notification success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification__close').innerHTML).toContain(
      '3s',
    );
    notificationService.success('notification success1');
    fixture.detectChanges();
    notificationService.success('notification success2');
    fixture.detectChanges();
    notificationService.success('notification success3');
    fixture.detectChanges();
    notificationService.success('notification success4');
    fixture.detectChanges();
    notificationService.success('notification success5');
    fixture.detectChanges();
    expect(ocEl.querySelectorAll('.aui-notification').length).toEqual(6);
  });

  it('should show a success notification with  string', () => {
    notificationService.success('notification success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification').classList).toContain(
      'aui-notification--success',
    );
    expect(
      ocEl.querySelector('.aui-notification__content').textContent,
    ).toContain('notification success');
  });

  it('should show a success notification with object', () => {
    notificationService.success({
      content: 'notification success object',
    });
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification').classList).toContain(
      'aui-notification--success',
    );
    expect(
      ocEl.querySelector('.aui-notification__content').innerHTML,
    ).toContain('notification success object');
  });

  it('should show a success notification with template', () => {
    notificationService.success({
      contentRef: fixture.componentInstance.templateRef,
      duration: 10_000,
    });
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-notification button')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification button').classList).toContain(
      'temp-btn',
    );
    expect(ocEl.querySelector('.aui-notification__close').innerHTML).toContain(
      '10s',
    );
  });

  it('should show a success notification with component', () => {
    notificationService.success({
      contentRef: NotificationContentComponent,
    });
    fixture.detectChanges();

    expect(
      ocEl.querySelector('.aui-notification .notification-demo-content'),
    ).not.toBeNull();
    expect(
      ocEl.querySelector('.aui-notification .notification-demo-content')
        .innerHTML,
    ).toContain('demo content');
  });
});