Examining for a TypeError with Typescript and Jasmine

In my current project, I am faced with the challenge of writing unit tests in Typescript for an existing library that was originally written in plain JS. Most of our page logic is also written in plain JS. Some functions in this library throw exceptions if incorrect types are passed as input. For example:

Collection.pluck([{"a":1},{"a":2}], "a") // Extracts values from a list of objects
> [1, 2]

The second argument in the above code snippet should be a string representing the property name from which to retrieve the values. The pluck function performs type checking to ensure that an array of objects has been provided, and it throws a TypeError if the check fails.

To write a test ensuring that the correct type of object is passed to the function, I would typically do so in plain JS as follows:

expect(function(){ Collection.pluck([{"a":1},{"a":2}], 0); }).toThrowError(TypeError);

However, my declaration file specifies the function signature like this:

declare namespace Collection {
    function pluck(obj: Object, propertyName: string): any;
}

When attempting to write the same test in TypeScript, I encounter a compilation error:

So, my question is: how can I achieve the desired outcome without making changes to the original function? Is there a way to configure TypeScript to ignore this specific issue only within this file?

Answer №1

If you have the ability to modify the test, consider passing the second argument as a string.

expect(function(){ Collection.pluck([{"a":1},{"a":2}], '0'); }).toThrowError(TypeError);

UPDATE: Since you are utilizing TypeScript, which performs type checking during compilation (transpilation to JS) by specifying types in function declarations, your code should already meet the test requirements. If you wish to verify types through unit testing, focus on cases where the type is designated as 'any' since these will not be validated during compilation. OR refer to this discussion for more insights: Unittesting in TypeScript

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

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Using node-fetch version 3.0.0 with jest results in a SyntaxError stating that import statements cannot be used outside a module

Recently, I've been updating my API to utilize node-fetch 3.0.0. One major change highlighted in their documentation is that node-fetch is now a pure ESM module. Click here for more information on the changes This update caused some of my unit tests ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

Adjusting table to include hashed passwords for migration

How can I convert a string password into a hash during migration? I've tried using the following code, but it seems the transaction completes after the selection: const users = await queryRunner.query('SELECT * FROM app_user;'); user ...

Tips for defining a key: reducerFunctions object within a Typescript interface

Exploring the given interface: interface TestState { a: number; b: string; } My goal is to create a generic type that enforces an object to: have the same keys as a specified interface (e.g. TestState) for each key, provide a value of a reducer funct ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

Converting the information retrieved from Firebase into a different format

My Project: In my Angular SPA, I am trying to retrieve data from Firebase and display specific values on the screen. Approach Taken: The data returned from Firebase looks like this: Returned Data from Firebase Error Encountered: In order to display the ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...

Using asynchronous functions in a loop in Node.js

Although this question may have been asked before, I am struggling to understand how things work and that is why I am starting a new thread. con.query(sql,[req.params.quizId],(err,rows,fields)=>{ //rows contains questions if(err) throw err; ...

Creating a Variety of Files in the Angular Compilation Process

Currently, I am developing an Angular project and faced with the task of creating various files during the build process depending on certain conditions or setups. I would appreciate any advice on how to accomplish this within the Angular framework. I att ...

Navigating through ionic2 with angularjs2 using for-each loops

I developed an application using IONIC-2 Beta version and I am interested in incorporating a for-each loop. Can anyone advise if it is possible to use for each in Angular-V2? Thank you. ...

The Firebase EmailPasswordAuthProvider is not a valid type on the Auth object

When working in an Angular2/TypeScript environment, I encountered an error when trying to use the code provided in the Firebase documentation. The error message displayed was "EmailPasswordAuthProvider Does Not Exist on Type Auth". var credential = fireba ...

Strategies for passing multiple props to a function in React using TypeScript, such as useState([]) and useState(boolean)

Dealing with API Structure { "default": [ { "id": 1, "name": "A" }, { "id": 2, "name": "B" }, { "id": 3, "name" ...

Waiting for the execution of the loop to be completed before proceeding - Typescript (Angular)

There's a code snippet triggered on an HTML page when clicked: public salaryConfirmation() { const matDialogConfig: MatDialogConfig = _.cloneDeep(GajiIdSettings.DIALOG_CONFIG); this.warningNameList = []; for(let i=0; i < this.kelolaDat ...

Creating a JSON file from a custom key-value class in Typescript: A comprehensive guide

I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class: export class TranslatedFileElement { private key: string private hasChild: boolean priva ...

The output of `.reduce` is a singular object rather than an array containing multiple objects

Building on my custom pipe and service, I have developed a system where an array of language abbreviations is passed to the pipe. The pipe then utilizes functions from the site based on these abbreviations. Here is the parameter being passed to the pipe: p ...