GitLab pipeline reveals failure in Angular testing

I'm encountering an issue with my pipeline, where a front-end unit test is failing in the pipeline but passes locally when running the 'yarn test' command.

Below is my test file:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { MyComponent } from './my.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [SharedModule, NoopAnimationsModule]
    })
      .compileComponents();
  }));

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


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

});

My component file :

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-compo',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
})
export class myComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

It's worth noting that this is a new component.

Here is the failure log from GitLab:

PhantomJS 2.1.1 (Linux 0.0.0) MyComponent should create FAILED
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown
PhantomJS 2.1.1 (Linux 0.0.0): Executed 112 of 185 (1 FAILED) (0 secs / 1 min 25.792 secs)
PhantomJS 2.1.1 (Linux 0.0.0) MyComponent should create FAILED
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown
PhantomJS 2.1.1 (Linux 0.0.0) MyComponent should create FAILED
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown
TypeError: undefined is not an object (evaluating 'this.get_container_ul()[0].className') thrown

I am using Angular v8.

Thank you.

Answer №1

Running a browser on a server may not be feasible, but fear not - Headless Chrome is here to save the day! This nifty tool allows you to run automated tests without actually launching a browser. To set it up, simply add the following config to your karma.conf.js:

browsers: ['Chrome_no_sandbox'],
customLaunchers: {
 Chrome_no_sandbox: {
 base: 'Chrome',
 flags: ['--no-sandbox', '--headless', '--disable-gpu', '--remote-debugging-port=9222', '--single-run']
 }
}

If Headless Chrome isn't your cup of tea, another option is to use PhantomJS.

  • Start by installing karma-phantomjs-launcher
  • Then, add PhantomJS to the list of plugins:

    plugins: [
     require('karma-jasmine'),
     require('karma-chrome-launcher'),
     require('karma-phantomjs-launcher'), // here
     require('karma-jasmine-html-reporter'),
     require('karma-coverage-istanbul-reporter'),
     require('@angular/cli/plugins/karma')
    ],
    
  • Finally, make PhantomJS the browser of choice:

    browsers: ['PhantomJS'],
    singleRun: true
    

Answer №2

One potential solution to your GitLab pipeline issue is to execute the command npm run build-prod within your project directory. This command can help identify and fix any errors that may be causing issues. Unlike the ng serve command, which simply runs the Angular application and may not catch all errors, ng build will check for Tslint errors, logical errors, and provide more detailed feedback on any issues that arise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Stop the upload progress in Angular 6 by unsubscribing from the upload observable, without halting the actual

When attempting to cancel an upload by unsubscribing, the unsubscribe action only stops the progress of the upload from being displayed, but the actual upload process continues and files are still uploaded to the server. This issue is present in the upload ...

Filling the text and value array using a collection of objects

Need help with populating an array of text and value using an array of objects in Angular. Below is the JSON data containing the array of objects. Declaration public AuditYearEnd: Array<{ text: string, value: number }>; Assignment - How can I assi ...

Error encountered: "Unable to locate module 'typescript-Collections' when modifying the module to "umd" or "amd" in the tsconfig.json file."

I recently upgraded to VS17 Enterprise and encountered an issue when trying to import the TypeScript Collections library from GitHub. After following the instructions on their page, I realized that changing the module option in my tsconfig.json file to eit ...

Learn how to apply CSS styles from one component to another in Angular

I am attempting to modify the background color of a wrapper from a different component. I tried using ::ng-deep but it's not functioning correctly. For the mauto component, the background should be a solid block color. For the vgud component, the back ...

Tricks to access value from a Nativescript array of Switch elements when tapping a Button

Scenario: In my project, I am using Nativescript 5.0 with Angular. The data is fetched from an API and displayed in customers.component.ts I am successfully rendering the elements based on the received IDs in customers.component.html When the user inter ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...

Looking to switch up the menu in Angular 6

Looking to toggle the side navigation bar, I have: Created a boolean variable toggle_menu set to true Added a function togg() on button click in the menu bar that sets the boolean value to false and toggles the div However, here's the iss ...

Managing the token prior to the page loading: best practices

Implementing JWT for authentication without a login page has posed some challenges for me. The issue arises when the site loads and immediately starts with the GET methods to load content before authenticating and saving the token in local storage. The pr ...

Unable to initialize the ng2-admin Angular2 Bootstrap template on a Go server due to a failed download attempt

Hello everyone, I am a newcomer to this forum and have limited experience with Angular2 and Golang. I am currently facing an issue as I want to experiment with a template on a Go server. To tackle this, I created a main.go file that includes the followin ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Iterate over the key-value pairs in a loop

How can I iterate through a key-value pair array? This is how I declare mine: products!: {[key: string] : ProductDTO}[]; Here's my loop: for (let product of this.products) { category.products.push((product as ProductDTO).serialize()); } However, ...

Should ts-node be avoided in a production environment due to potential risks?

My current setup involves using ts-node with express in production and so far, it's been functioning smoothly. Am I missing out on any benefits by not compiling and running .js files instead? ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...