Basic Karma setup with Typescript - Error: x is undefined

I am trying to configure a basic test runner using Karma in order to test a TypeScript class.

However, when I attempt to run the tests with karma start, I encounter an error stating that

ReferenceError: Calculator is not defined.
It seems like either the karma runner is not importing the transpiled source file or the preprocessor is failing to transpile the source code.

You can find my source code in this repository here, and the relevant parts are provided below. Can you help me figure out how to configure my setup properly?

Based on my current understanding, both the transpiler and the 'files' configuration property in karma should be loading the calculator class for me.

export class Calculator{
  add ( a : number , b : number) : number {
    return a + b;
  } 
}

/test/calculator.test.js

describe('Demo Test Runner', function() {
  var calc = new Calculator();
  it('should return 3 for 1 + 2', function() {
   expect( calc.add(1,2) ).toBe(3);
  });
});

package.json

...
"devDependencies": {
  "jasmine-core": "^2.5.2",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-jasmine": "^1.0.2",
  "karma-typescript-preprocessor": "^0.3.0"
}

karma.conf.js

module.exports = function(config) {
 config.set({

 ...
 frameworks: ['jasmine'],

 files: [
    'lib/**/*.js',
    'test/**/*.js'
  ],

 preprocessors: {
   '**/*.ts': ['typescript']         
 },

 typescriptPreprocessor: {
    // options passed to the typescript compiler 
    options: {
      sourceMap: true,
      target: 'ES5',
      module: 'amd',
      noImplicitAny: true,
      noResolve: true,
      removeComments: true,
      concatenateOutput: false
    },
    // transforming the filenames 
    transformPath: function(path) {
      return path.replace(/\.ts$/, '.js');
    }
 }
 ...

Answer №1

When you define your calculator as

export class Calculator{...}

This indicates that your /lib/calculator.ts is a module and its classes must be imported by other modules in order to be visible (they are not global).

Therefore, your /test/calculator.test.js needs to somehow import this module. The method for doing so will depend on the module configuration in your tsconfig.json

In your situation, you may want to use either "module" : "commonjs" or "module": "amd".

However, you will require an additional plugin for karma to load these modules. If using amd, something like karma-requirejs would be necessary; for commonjs, you might need something like karma-webpack. Then, you would need to utilize the appropriate syntax to import it in your js file (e.g.

var MyCalculator = require('/lib/calculator');
)

Your other option is to not "export" your Calculator class, making it globally accessible. However, it is advisable to try and make the module approach work as that is recommended for larger applications.

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 is the best way to utilize the Moment.js TypeScript definition file in a website that already has moment.min.js integrated?

Currently, I am in the process of transitioning a website to utilize TypeScript by converting one JavaScript file at a time. All pages on my site are already linked to moment.js, such as: <script src="/scripts/moment.min.js"></script> I have ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

In TypeScript, what is the return Type of sequelize.define()?

After hearing great things about TypeScript and its benefits of static typing, I decided to give it a try. I wanted to test it out by creating a simple web API with sequelize, but I'm struggling to understand the types returned from sequelize. Here ar ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

Angular Fusion: Delay execution of ngAfterViewInit until data is received from API call in ngOnInit

I'm facing an issue with my code where the API call in ngOnInit is not waiting for the data to be returned before moving on to ngAfterViewInit. I need it to wait because I am performing operations on that data in ngAfterViewInit, but currently, it&apo ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Error: The function $.cookie() is not defined in Angular2 Typescript

After installing @types/jquery, I updated tsconfig.json to include jquery.cookie in the types section. Visual Studio Code indicates that $.cookie is ready for use, but when I execute my code, an error appears in the console stating that $.cookie() is not ...

What are the Typescript object types where the keys are functions that take a single generic argument consistently?

Explaining this concept in English is quite challenging, but here's what I'm aiming for: const operations = { store: (input: T): T => { return input; }, discard: (input: T): void => { console.log(input); } } In both fun ...

How can a particular route parameter in Vue3 with Typescript be used to retrieve an array of strings?

Encountered a build error: src/views/IndividualProgramView.vue:18:63 - error TS2345: Argument of type 'string | string[]' is not assignable to parameter of type 'string'. Type 'string[]' is not assignable to type 'strin ...

Tips for uploading the IDENTICAL file in angular4

After successfully uploading a file, I encountered an issue where the system does not allow me to upload the same file twice. Here is the code snippet related to the problem: <input type="file" (change)="onFileChange($event)" name="fileUploaded" value ...

The error in Angular states that the property 'length' cannot be found on the type 'void'

In one of my components, I have a child component named slide1.component.ts import { Component, Input, OnInit, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-slide1', templateUrl: './slide1.component. ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

Encountering issues with accessing a variable before its initialization in the getServerSideProps function in

Currently, I am working on setting up Firebase and configuring the APIs and functions to retrieve necessary data in my firebase.tsx file. Afterwards, I import them into my pages/index.tsx file but I am encountering an issue where I cannot access exports af ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...