Tips for setting up karma to allow for the debuggability of TypeScript source files

I recently downloaded an Angular2 Webpack Starter seed project from GitHub and managed to set it up without encountering any issues. However, I have run into a slight inconvenience when trying to debug source files under unit tests. All *.spec.ts files are loaded directly into the browser and can be debugged, but no map files are generated for them. When stepping into a source file under test, this is the result:

https://i.sstatic.net/W84nh.png

Below is my karma config:

module.exports = function(config) {
var testWebpackConfig = require('./webpack.test.js');

config.set({
    basePath: '',
    frameworks: ['jasmine'],
    exclude: [ ],
    files: [ { pattern: './config/spec-bundle.js', watched: false } ],
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },
    webpack: testWebpackConfig,
    coverageReporter: {
      dir : 'coverage/',
      reporters: [
        { type: 'text-summary' },
        { type: 'json' },
        { type: 'html' }
      ]
    },
webpackServer: { noInfo: true },
reporters: [ 'mocha', 'coverage' ],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [
  'Chrome'
],
singleRun: false
});
};

And here is the webpack.test.js configuration:

const helpers = require('./helpers');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ENV = process.env.ENV = process.env.NODE_ENV = 'test';
module.exports = {
    devtool: 'inline-source-map',
    resolve: {
        extensions: ['', '.ts', '.js'],
        root: helpers.root('src'),
    },
    module: {
    preLoaders: [
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [helpers.root('node_modules')]
      },
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
            helpers.root('node_modules/rxjs'),
            helpers.root('node_modules/@angular2-material'),
            helpers.root('node_modules/@angular')
      ]}
   ],
// more configurations
}

The spec-bundle.js file:

Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
require('rxjs/Rx');
// more imports and functions

I am seeking advice on how to modify this setup so that the .ts source files are debuggable with accurate coverage statistics. Any suggestions or guidance would be greatly appreciated. Thank you!

Answer №1

Dealing with a similar issue in my own project (not Angular2 Webpack Starter, but likely facing the same root cause).

It seems that by default, Karma does not pass source maps when using WebPack unless the file extension is either .js or .jsx for React projects. In this scenario, Karma and WebPack simply transpile .ts (or .tsx) files from TypeScript to JavaScript without generating source maps.

I managed to resolve this problem after finding a helpful solution on the GitHub Issues page for karma-webpack. The trick was to include the webpack.SourceMapDevToolPlugin with an expanded file filter in the webpack configuration. For you, it should resemble something like this:

var webpack = require('webpack');
// Inside your config.set:
plugins: [
  // Add existing plugins here
  new webpack.SourceMapDevToolPlugin({
    filename: null, // Sourcemap will be inlined if no value is provided
    test: /\.(ts|js)($|\?)/i // Only process .js and .ts files
  })
]

Answer №2

To disable the Istanbul loader in your webpack.test.config.js file, you can comment it out as shown below:

    // {
    //   enforce: 'post',
    //   test: /\.(js|ts)$/,
    //   loader: 'istanbul-instrumenter-loader',
    //   include: helpers.root('src'),
    //   exclude: [
    //     /\.(e2e|spec)\.ts$/,
    //     /node_modules/
    //   ]
    // }

After making this change, simply execute the following command:

 npm run watch:test

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

Deactivating a Component in Ionic Angular

I am interested in including a CanDeactivate Guard in my Ionic Angular project. After reading about the new "CanDeactivateFn" Guard, I have been unable to find any information or examples on how to implement it. Could someone provide me with an example? ...

"Utilize Ionic to subscribe the back button and close an internal div with ease

I have a div called "Search Filters" that appears when the condition this.show_filters == true is met. I am now attempting to use the Android back button to change this variable to false. async toggleFiltersWindow(){ console.log('#1 toggleFilters( ...

the pause in execution before my function redirects to a different route

Currently, I am developing a page using nodeJs with express which is supposed to display a table. However, I encountered an issue with my variable "allMusique" that contains the data for my page. When trying to access it initially, there seems to be an err ...

The function io.sockets.in(roomName) does not seem to be properly listening for myEvent after joining the

I am looking to dynamically create rooms based on incoming requests from the front end. I found guidance in this gist. My goal is for a specific room to listen for events and communicate with other members within that room. However, I am experiencing an i ...

"Encountering an issue with TypeScript test files being blocked while utilizing the karma-webpack

I have been encountering an issue while trying to utilize karma-webpack for compiling my typescript tests in conjunction with karma. Lately, my tests have ceased running. When inspecting the developer console, I come across messages like the following, fo ...

Closing on submit the modal window

I'm encountering an issue with a form in a bootstrap modal window. When I click the 'send' button, the modal closes and displays a white page with the error message from my action call to contact-form.php. However, the error message should a ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Can a div be relocated within another div based on a random roll of the dice?

Hey there, I'm currently working on creating a simple Monopoly-style game. As someone who is pretty new to JavaScript, I'm looking to figure out how to move the game piece around the board based on dice rolls. Any guidance or assistance would be ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Is there a way to ensure that a popup is scaled in proportion to its content?

Is there a way to make external links open in a new window with a size relative to the parent window, making it clear to the user? I initially used the target attribute but found a workaround like this: <a href="http://example.org" onclick="window.op ...

The Serialization problem in next.js when using getStaticProps

While working on my project with next.js, I encountered an issue where the axios fetch in getStaticProps wasn't functioning properly even though the URL was serialized in the configuration. I attempted to serialize it again by passing the response to ...

Extracting data from a JSON store in Ext JS 4.1.3: A step-by-step guide

In my Ext.data.Store, I have language variables stored in JSON format like this: { "language":"en_GB", "data":[ {"fieldName":"browserInfo","fieldValue":"Descriptive text"} ] } This is the store I've set up: Ext.local.langStore ...

Activate the q-file toggle for the Quasar framework when a different button is selected

How can I make the file selector q-file toggle in Quasar framework when a specific button is clicked? My current attempt: When this button is clicked, it should toggle the q-file: <button @click="toggleFileSelector">Toggle File Selector&l ...

What's the best way to ensure that your item list automatically updates the rendered list when an item is deleted

I've developed a web cart using Redux. The cart functions as expected, except for one issue - when I delete an item from the cart, the changes are only displayed after refreshing or navigating to another page. How can I update the view dynamically as ...

Creating an interface that extends the Map object in TypeScript to maintain the order of keys

After learning that the normal object doesn't preserve key order in TypeScript, I was advised to use Map. Nevertheless, I'm struggling to figure out how to assign values once I've declared the interface. Take a look at my approach: Coding ...

What is the rationale behind TypeScript permitting undefined methods?

Currently, I am working on a presentation for my development team about TypeScript. I want to demonstrate the importance of type checking through examples, but I'm stumped as to why this particular piece of code is not throwing a compile-time error wh ...

Adjust the message background color once it has been viewed

One of the buttons attached to a mat-menu has a red background when clicked. If you want to see it in action, check out this Stackblitz. .list-item.error { background-color:#FCE8FF; } However, if the button is clicked more than two times, the color sh ...

When utilizing useEffect in Next.js, an error may occur stating that the window is

It seems like there is a challenge with executing script code server side in next.js 13 when it needs to be executed client side. Currently, I am trying to implement the bulma calendar found at When importing the required library: import PasswordStrengthB ...

Accessing the placeholder attribute value of an ngcontrol in a TypeScript .ts file

I have encountered an issue where the placeholder attribute is showing as undefined in a TypeScript .ts file. Here is the code snippet I wrote: HTML Code- <label class="lab1">Closing date</label> <input placeholder="M/d/yyyy" type="text" [ ...

I am having trouble unzipping the file

I encountered an issue while attempting to download a .zip file from Discord and extracting it using the decompress package. Despite not returning any errors, the package did not get extracted as expected. (The file was saved and downloaded correctly) co ...