Skip to content

angular testing

devonfw-core edited this page Jan 27, 2022 · 4 revisions

Angular testing

testing

MyThaiStar testing is made using Angular default testing environment and syntax language: Karma and Jasmine

To test an element of the application, you indicate that tests are a special type of files with the extension .spec.ts, then, in MyThaiStar angular/CLI config you can notice that there is an array with only one entry, Karma, with at the same time has one entry to Karma.config.js.

In the configuration of Karma we indicate which syntax language we are going to use (currently Jasmine as said before) between some other configurations, it is remarkable the last one: browsers. By default, the only available browser is chrome, that is because Karma works opening a chrome view to run all the tests, in that same window, Karma shows the result or errors of the test run. But we can add some other browser to adjust to our necessities, for example, in some automatic processes that run from console, it is not an option to open a chrome window, in that case, MyThaiStar used PhantomJS and ChromeHeadless.

Taking all of this into account, to run the test in MyThaiStar we need to move to project root folder and run this command : ng test --browser <browser>

Note

If you run just ng test it will run the three browser options simultaneously, giving as a result three test runs and outputs, it can cause timeouts and unwanted behaviors, if you want a shortcut to run the test with chrome window you can just run yarn test so we really encourage to not use just ng test.

Here we are going to see how Client side testing of MyThaiStar has been done.

Testing Components

Angular components were created using angular/CLI ng create component so they already come with an spec file to test them. The only thing left to do is to add the providers and imports needed in the component to work as the component itself, once this is done, the most basic test is to be sure that all the dependencies and the component itself can be correctly created.

As an example, this is the spec.ts of the menu view component:

all the imports...

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MenuComponent, MenuCardComponent ],
      providers: [SidenavService, MenuService, SnackBarService],
      imports: [
        BrowserAnimationsModule,
        BackendModule.forRoot({environmentType: 0, restServiceRoot: 'v1'}),
        CovalentModule,
      ],
    })
    .compileComponents();
  }));

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

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

First we declare the component to be tested and a Fixture object, then, we configure the testingModule right in the same way we could configure the MenuModule with the difference here that tests always have to use the mock back-end because we do not want to really depend on a server to test our components.

Once configured the test module, we have to prepare the context of the test, in this case we create the component, that is exactly what is going on in the beforeEach() function.

Finally, we are ready to use the component and it’s fixture to check if the component has bee correctly created.

At this moment this is the case for most of the components, in the future, some work would be applied on this matter to have a full testing experience in MyThaiStar components.

Dialog components

Dialog components are in a special category because they can not be tested normally. In the way Material implements the opening of dialogs, you have to create a component that will load into a dialog, to tell the module to load this components when needed, they have to be added into a special array category: EntryComponents. So, to test them, we need to import them in the test file as well.

Also, the testing code to open the component is a bit different too:

...
  beforeEach(() => {
    dialog = TestBed.get(MdDialog);
    component = dialog.open(CommentDialogComponent).componentInstance;
  });
...

That is right, the beforeEach() function is slightly different from the the example above, in this case we have to force to the test to know that the component is only displayed in a dialog, so we have to open a dialog with this component in order to access it.

Testing Services

As well as components, services can be tested too, actually, they are even more necessary to be tested because they have inside more complex logic and data management.

As an example of testing services i am going to use a well done services, with a specific purpose and with its logic completely tested, the price-calculator service:

...

describe('PriceCalculatorService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [PriceCalculatorService],
    });
  });

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

  describe('check getPrice method', () => {

    it('should calculate price for single order without extras', inject([PriceCalculatorService], (service: PriceCalculatorService) => {
      const order: OrderView = {
        dish: {
          id: 0,
          price: 12.50,
          name: 'Order without extras',
        },
        orderLine: {
          comment: '',
          amount: 1,
        },
        extras: [],
      };

      expect(service.getPrice(order)).toEqual(order.dish.price);
    }));
...

In services test, we have to inject the service in order to use it, then we can define some initializing contexts to test if the functions of the services returns the expected values, in the example we can see how an imaginary order is created and expected the function getPrice() to correctly calculate the price of that order.

In this same test file you can find some more test regarding all the possibilities of use in that services: orders with and without extras, single order, multiple orders and so on.

Some services as well as the components have only tested that they are correctly created and they dependencies properly injected, in the future, will be full covering regarding this services test coverage.

Testing in a CI environment

Clone this wiki locally