Testing the Compatibility of Angular JS and Angular 8 in a Hybrid Application

I am currently working on a hybrid application using AngularJS and Angular 8. The new components I create in Angular need to be downgraded for use in AngularJS. Here is a snippet of the module code:

@NgModule({
    // Declarations and Imports
    providers:[
        ServiceName,
        // Other Services
    ],
    entryComponents: [
        ComponentName,
        // Other components for use in AngularJS
    ]
})
export class FeatureModule{
}

declare var angular: angular.IAngularStatic
angular.module('app')
   .directive('cmpName', downgradeComponent({component: ComponentName }) as angular.IDirectiveFactory)
   .factory('serviceName', downgradeInjectable(ServiceName));

In the app.module.ts file, you will find the following code:

// Regular Code
export class AppModule {
  constructor(
    private upgrade: UpgradeModule,
  ) {
  }

  ngDoBootstrap() {
    this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
  }
}

No updates have been made to the component spec file generated by the Angular CLI.

The tsconfig.spec.json file looks like this:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "../out-tsc/spec",
    "types": ["jasmine", "node", "angular"]
  },
  "files": ["test.ts", "polyfills.ts"],
  "include": ["**/*.spec.ts", "**/*.d.ts"]
}

The karma.conf.js file has the following configuration:

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage/ProjectFolder'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};

When running the tests with npm run test or ng test, I encounter the error:

An error was thrown in afterAll Uncaught ReferenceError: angular is not defined ReferenceError: angular is not defined at Module../..path-to-module-file/feature.module.ts.

How can I resolve this issue? Do I need to mock the angular variable declared in the module file? Any assistance would be greatly appreciated.

Answer №1

My approach to running a hybrid application involves utilizing Webpack and Karma. To ensure compatibility with AngularJS, I make it a point to downgrade all components similar to what you do.

The key distinction lies in the presence of a specific file named vendor.ts that houses AngularJS functionalities. It seems likely that you have this file as well since your focus is primarily on test failures rather than overall product malfunction. In my Karma configuration file, I include an entry specifying files to be watched:

    // List of files to be watched by Karma
    files: [
      { pattern: "node_modules/babel-polyfill/dist/polyfill.js", watched: false },
      { pattern: "node_modules/intl/locale-data/jsonp/en-GB.js", watched: false },
      { pattern: "node_modules/intl/locale-data/jsonp/fr-FR.js", watched: false },
      // More file patterns listed here...
    ],

This setup allows Karma to monitor and serve specific files in the browser environment. Essentially, after Webpack completes the compilation process, Karma-Webpack can locate these compiled files for seamless serving.

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

Filtering the JSON data shown according to an array in Angular 7

After receiving JSON data from the backend using a service, I am displaying it through a loop in main.html. There is an array that contains the values of a column being displayed. For example, if the array looks like this: colors=[red,blue], then only reco ...

Angular - Arranging a table within another table

I am currently dealing with nested tables and have an example dataset: $scope.building = [ { "id": 1, "name": "first", "ownBlock": [ { "id": 1, "name": "Block 1" }, { ...

After upgrading from angular-cli version 4 to version 7, the npm installation process stops working

I have been working on transitioning my Angular4 project to Angular7. Here are the steps I took in order to make this conversion: I first uninstalled the older version of angular-cli Next, I installed the latest updated version of angular-cli However, up ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

Angular JS requires a predefined list of values to be passed as a URL parameter

What I am attempting to accomplish: The parameter value should be one of a, b, c, d, e. If the parameter value is not in the provided list, the user should be redirected. This current implementation is causing an "Infinite $digest Loop" error. How can I ...

In Angular Mat Stepper, only allow navigation to active and completed steps

For a project, I created a sample using React.js and Material UI. Here is the link to the project: https://stackblitz.com/edit/dynamic-stepper-react-l2m3mi?file=DynamicStepper.js Now, I am attempting to recreate the same sample using Angular and Material, ...

Error encountered during package installation: npm command terminated with exit code 1

When working with Angular 2, I consistently encounter the same issue across all of my projects. Strangely, these issues are normally resolved when building on a different PC. view image description here ...

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

Setting up Nginx, Node, and Angular to work together with a subfolder in the API/

Currently, my node/angular application runs smoothly when directed to the configured port (8081 for explanation purposes). I am able to perform post, get, put, and delete operations as expected. My objective is to have the node application running on mydo ...

Using a single TypeORM connection across various modules in NestJS

In the process of developing a link shortener, I have set up a CRUD REST API for authentication and creating shortened links. Now, I am looking to manage redirects for these shortened URLs without using the same path as my API endpoints (e.g. /api/v1/). Af ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

Using IONIC2 to localize month names in the UI

I am encountering a challenge with ionic2 related to translating month names into Portuguese for Brazil. In my views, I utilize the date filter to display the full month names, but they are currently appearing in English. I need them to be displayed in Bra ...

Error notifications continue to appear despite the presence of data in the input field

I am utilizing a component to exhibit various information (such as first name, last name, phone number, etc.) fetched from the API. The main focus is on executing CRUD operations, particularly the update operation. Referencing the image below: An is ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

Encountered an error while attempting to compile a Node.js application for deployment on

Hello there! I encountered a peculiar issue after reinstalling everything on my laptop. Now, I'm facing trouble every time I try to push to Heroku using this package.json configuration. { "name": "mrfrederiksen", "version": "0.0.0", "license" ...

When transitioning to a different page, Angular is creating a duplicate of $scope

My webpage features a section where I showcase all the individuals stored in the database, referred to as the All Persons Page. Within this page, there are two primary options: Add New Person Delete Person (Any selected individual) An issue arises when ...

Creating a package exclusively for types on NPM: A step-by-step guide

I'm looking to set up a package (using either a monorepo or NPM) that specifically exports types, allowing me to easily import them into my project. However, I've run into some issues with my current approach. import type { MyType } from '@a ...

Angular 6 - Deleting the node_module package to streamline local project modifications

After reviewing our options, we have decided to implement ng2-smart-table for the table grid in our current project. However, we've encountered some limitations with its functionality that do not fully meet our project requirements. As a result, we a ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...