Encountered an issue while attempting to run tests on an Angular2 component using an external template

I've been exploring unit testing in an Angular2 application and following the guidance provided by the Angular documentation. However, I've encountered a perplexing error that has stumped me.

To experiment with testing, I've set up a simple demo app mirroring the configuration of my larger project. This Angular2 app is integrated with ASP.NET Core MVC using templates and setup from this link: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ASPNETCoreTemplatePack. The tech stack includes Webpack, Typescript, Karma, and Jasmine for handling unit tests.

The issue arises when I attempt to write tests for a component featuring an external template as described in this documentation. Although all my tests pass smoothly, an error occurs in my editor and during the application's execution. The specific error message reads:

error TS2345: Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'.

While resolving the error remains my top priority, I'd also appreciate setting up the environment so that my .spec.ts files are excluded from the bundles created by Webpack for the production site (noting that these spec.ts files reside alongside the .ts files implementing the components).

Here is an example of one of the test files, banner.component.spec.ts:

karma.conf.js:

'use strict';

module.exports = (config) => {
    config.set({
        autoWatch: true,
        browsers: ['Chrome', 'PhantomJS'],
        files: [
            './node_modules/es6-shim/es6-shim.min.js',
            './karma.entry.js'
        ],
        frameworks: ['jasmine'],
        logLevel: config.LOG_INFO,
        phantomJsLauncher: {
            exitOnResourceError: true
        },
        preprocessors: {
            'karma.entry.js': ['webpack', 'sourcemap']
        },
        reporters: ['progress', 'growl'],
        singleRun: false,
        webpack: require('./webpack.config.test'),
        webpackMiddleware: {
            noInfo: true
        }
    });
};

karma.entry.js

require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
...

webpack.config.test.js

'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    module: {
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            ...
        ]
    },
    resolve: {
        extensions: ['', '.js', '.ts'],
        modulesDirectories: ['node_modules'],
        root: path.resolve('.', 'ClientApp/app')
    }
};

webpack.config.js

/// <binding ProjectOpened='Watch - Development' />
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
...

Answer №1

It turns out I finally cracked the code on my problem. During the initial project setup, it seems I mistakenly installed an outdated version of '@types/jasmine', which had a different signature for the beforeEach() method that couldn't recognize the done:any returned by the async() function. After updating to the latest version of '@types/jasmine', all issues were resolved as it now supports the correct version of beforeEach().

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

Transitioning from asp net mvc to asp core + angular: Elevating your web development game

I am currently in the process of upgrading an older ASP.NET MVC application to a newer version using ASP Core + Angular 7. In the previous app, we had an external service that called our API and sent the auth token in the URL because it was unable to do ot ...

Updating the selected state of an Angular 2 material mat-chip

Attempting to update the selected property of a chip named "chip" results in an ExpressionChangedAfterItHasBeenCheckedError when changing the binding property. HTML <mat-chip-list> <mat-chip *ngFor="let w of weekDays" [selectable]="tru ...

Troubleshooting Firebase: How come my code is only accessing the initial document in my Collection?

After spending hours searching, I still can't find a solution to my problem with this code. The Firebase log file only shows: "after for each =undefinedsensor_location_1undefinedundefinedundefined " Why is it only referencing the first do ...

Layout your Angular components with a column design using Flex Layout

Is there a way to adjust the width of a child component in an fxLayout set to column? Take this example for reference: https://stackblitz.com/edit/angular-fxlayout-custom-breakpoints?file=app%2Ftest.component.ts In the provided example, there are three f ...

When using Angular msal_angular in conjunction with an ASP.NET Core Web API, an error may occur indicating an invalid token

I developed my Angular application using the guide provided in this example: https://github.com/microsoftgraph/msgraph-training-angularspa Successfully, I managed to log in and authenticate with MS Graph from within the Angular app. However, I am facing ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Encountered an Angular HPM localhost error while attempting to proxy a request for /api/books from localhost:4200 to http://localhost:3333

After spending several hours attempting to resolve this issue, I am still unable to successfully make a post request due to an error. Initially, I used ng serve, but switched to npm start and the errors persist. Error: [HPM] Error occurred while attempti ...

Preventing Browser Back Button Functionality in Angular 2

I'm currently working on an Angular 2 website and wondering if there is a way to either disable or trigger the browser's back button using Angular 2. Any insights would be greatly appreciated! ...

Can I modify a global array by updating a dynamically created array in the ngOnInit method of Angular?

Are there any suggestions on how to make a dynamic array available globally in Angular? I am currently using this codepen () which stores clicked countries in an array. The issue is that the array is nested within a function in ngOnInit and I need it to b ...

What causes Angular 4's ngModel to impact other variables?

While working with Angular 4 ngModel, I stumbled upon an amusing bug. Here's the scenario: this.restService.getProduct(this._id).subscribe( response => { this.product = response; this.productCategory = response.category; ... In the t ...

A guide on effectively testing the value of Object.constructor using Jasmine and minimizing redundancy in the it statements for AngularJS

In my AngularJS application, I have defined an object model like this: .factory('Watermark', function () { // Constructor, with a class name // Assumption: the backend provides us with a topic or not! function Watermark(content, tit ...

Testing attributes and props with React Testing Library

Currently, I am in the process of developing a React application using TypeScript. For creating components, I rely on material-ui and for unit testing, I make use of react-testing-library. Specifically, I am working on designing a wrapper for the Grid com ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

Is there a way to display unused imports and locals as warnings instead of errors in vscode?

When I'm writing TypeScript code in my code editor, it highlights unused imports and local variables as errors, marked with a red squiggly underline: https://i.sstatic.net/zRJMP.png However, I would prefer if these were shown as warnings in the edit ...

What is the best way to execute a specific set of unit tests in Gulp-Angular using Karma?

In the midst of my AngularJS 1.4 project, fashioned through the Gulp-Angular yeoman generator, I find myself facing a dilemma. With karma and gulp settings already in place, executing gulp test runs all *.spec.js files within the project. However, my desir ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

Run the code before the http observable initiates the network request

Is there a way to write code that executes before an Angular HTTP client observable makes a network call, but after the function is called? The following code snippet shows an example of an Angular HTTP service call: this.geocodeApi.getAddressSuggestions( ...

Retrieving targeted information from the store following the retrieval of data from an API

In my project, I have set up an RXJS effect that loads an organization from the server upon a certain action. Once the organization is loaded, I attempt to select a bookmark from the NGRX store based on the organization ID. Finally, I dispatch a success ac ...

"How to include a JavaScript file from the node_modules folder in an Angular project

Currently, I am working on integrating an npm package called svgedit into my angular app. The installation of the package was successful; however, when attempting to reference a JavaScript file, I encountered the following error: net::ERR_ABORTED 404 ( ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...