Web application error: Karma and Webpack cannot locate Angular controller

After following a blog post on setting up an Angular project with webpack, I used an associated boilerplate on Github.

Although the app is functioning properly, Karma seems to have trouble finding the controller it needs to test.

// karma.config.js
module.exports = config => config.set({
  files: ['test.webpack.js'],
  preprocessors: {
    'test.webpack.js': ['webpack', 'sourcemap']
  },
  browsers: ['PhantomJS2'],
  webpack: require('./webpack.config'),
  webpackMiddleware: {
    noInfo: 'errors-only',
  },
});

// test.webpack.js
import 'angular';
import 'angular-mocks/angular-mocks';

const testContext = require.context('./', true, /\.spec\.js$/);
testContext.keys().forEach(testContext);

Currently, I only have one spec file named MainCtrl.spec.js. Although Karma attempts to run it, I receive the error:

Argument 'MainCtrl' is not a function, got undefined

Interestingly, when I run the actual application, MainCtrl loads without any issues. It's perplexing why Karma can't access it.

I've experimented with changing \.spec\.js to simply \.js, but this approach leads to numerous other errors.

Answer №1

A different approach helped me overcome this obstacle. Two key challenges I faced were that the module was not being globally exported from ngMocks due to conflicts with the node import system. Additionally, the tests needed to load all module files first, a common requirement for Karma.

// Updated karma.config.js
files: ['app/index.js', 'test.webpack.js']
preprocessors: {
  'app/index.js': ['webpack'],
  'test.webpack.js': ['webpack'],
}


// Revised test.config.js
/* Angular is already imported by app/index.js */
import 'angular-mocks/angular-mocks';

/* Remember to use `angular.mock.module` instead of simply `module` */    
beforeEach(angular.mock.module('ngculator'));
const testContext = require.context('.', true, /\.spec\.js$/);
testContext.keys().forEach(testContext);

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

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

Experiencing difficulties loading webpages while attempting to execute Routes sample code using NodeJS

As a beginner in Javascript, I am attempting to execute the example code provided in the documentation for routes. The code snippet is as follows: var Router = require('routes'); var router = new Router(); router.addRoute('/admin/*?&apos ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Setting attributes on an AngularJS Directive element in real time

My goal is to create a directive in AngularJS with a template that can contain other AngularJS directives. All of my directives require an "id" attribute, so I must set the "id" on the directive within the template. However, no matter how I attempt this, A ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Error in Discord.JS: The function message.author.hasPermission is not recognized

As I was working on creating a new command for my discord.js bot to toggle commands on/off, I ran into some issues. Specifically, when I attempted to use the .hasPermission function, I encountered the following error message: TypeError: message.author.ha ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests. Below is the nginx configuration located within the sites-enabled directory ...

Tips on how to eliminate items from a list that do not include a specific character

I need help with a list that has a specific format /listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline-sunroof-hayalet-819608311/detail,#,#,,/listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline ...

Executing script once the DOM has completed loading

In my project, I'm dynamically generating menu items for a menu bar based on headers from external files that are imported using an XMLHttpRequest(). The menu bar is then updated as I navigate through different pages. Everything works smoothly. Each ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

"Design the website with a WYSIWYG editor while preventing users from disrupting the page's

I am considering using an HTML WYSIWYG editor like CKEditor, but I am concerned about the possibility of users submitting HTML code that could alter the layout of the page when rendered. Here is a comparison between two posts: <p><b>This is m ...

Facing a cross-domain problem that is blocking my ajax request to fetch data from my express endpoint

Looking to retrieve and showcase data from my node/exprss file (app.js) on my index.html. Utilizing an ajax request to localhost:3000/turtles in frontend.js, but running into cross domain obstacles. APP.JS FILE var express = require('express'); ...

Create a CSV file through an MVC Web API HttpResponse and retrieve it using AngularJS for downloading

I am attempting to create a CSV file from my web API and retrieve that file using angularjs. Below is an example of my API controller: [HttpPost] public HttpResponseMessage GenerateCSV(FieldParameters fieldParams) { var output = new byte[ ...