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

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

The left side of the form input material is obscured unless the necessary criteria are fulfilled

I am currently in the process of developing the front-end for a web application using the material library. The issue I am facing is that when a field does not meet its requirements, such as needing to enter a 'bedrijfsnaam', the border turns red ...

Angular 2 routing malfunctioning

I'm encountering an issue while setting up routing in my application. The error displayed in the console is as follows: angular2-polyfills.js:138 Error: XHR error (404 Not Found) loading http://localhost:9000/angular2/router.js(…) Below is the co ...

Customizing Angular with SASS Theming

After coming across the query How can switchable themes be implemented in SCSS?, particularly the second response which drew inspiration from this insightful Medium post, I decided to try implementing themes using SASS on my project. Unfortunately, I hav ...

The module 'AppModule' has unexpectedly declared a value of 'Component' that was not anticipated

Recently, I've been working on transitioning my application to the new angular2 webpack rc5 setup. I have successfully generated the app module using ng cli migration. However, I am facing an issue while trying to integrate a component from my own li ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

What is the best way to set up the --public-host for operating an Angular universal app in conjunction with an Ngin

Looking to implement HMR for a universal app, I want to confirm if it is possible. I have successfully set up and run an Angular 8 application using the default "ng new" command. To run it behind a reverse proxy, I modified npm start as follows: e.g. { " ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

Switch the sidebar position to the right in the ngx-admin interface created by Nebular

I need to customize ngx-admin to display in RTL style with the sidebar on the right. Despite conducting research, I have been unable to find a solution within this Github project. Can anyone offer assistance with this issue? ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike. Creat ...

Angular Validators.pattern() does not seem to function properly, despite yielding successful results in online regex testers

I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior. This regex pattern is meant for validating the Width input of a packag ...

Can an element be dynamically bound and unbound upon clicking a button in AngularJS?

After creating a display text and an input field, I bound them together using ng-model in the code below: HTML <div ng-app ng-controller="test"> <div ng-bind="content"></div> <input id="txtElem" type="text" ng-model="content" ...

Can anyone identify the problem with this Angular Js sample code?

I recently started learning angularJS and decided to create a calculator using this framework. The calculator consists of two combo boxes for input values and another combo box for selecting the operation to be performed. However, upon clicking the button, ...

unable to construct a Yeoman Angular application

Having some issues while building an AngularJS web app generated with Yeoman Angular generator. Running grunt serve works just fine, but when trying to build the app with grunt, encountering errors like: Running "concurrent:dist" (concurrent) task Warning ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

How to store selected checkbox values in an array using AngularJS

Check out this code snippet: <tr ng-repeat="doc in providers"> <td><input type="checkbox" ng-true-value="{{doc.provider.Id}}" ng-false-value="" ng-model="ids"></td> </tr> {{ids}} I am trying to store the values of ...