Using Jasmine to Jest: Mocking Nested function calls

I am currently working on testing my TypeScript functions with Jasmine:

//AB.ts

export async function A() {
}
export async function B() {
    A();
}

My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I have so far:

//AB.spec.ts
import * as AB from './AB'

describe('AB has a function B that ', () => {
    it('calls A', async () => {
        let ASpy: jasmine.Spy;
        ASpy = spyOn(AB, 'A').and.returnValue(Promise.resolve({}));
        await AB.B();
        expect(ASpy).toHaveBeenCalled();
    });
});

Upon running the test, I received an error indicating that ASpy was never called. However, after investigating further, I confirmed that the A function was indeed called. It seems like the mock I created for the function did not trigger as expected. I tried relocating the A function to a separate file and mocked it there for the test in AB.spec.ts; surprisingly, the test passed as the expectation showed that ASpy was called. I'm puzzled as to why having both functions in the same file caused the test to fail while separating them into different files made it pass. I would appreciate any insights or help on this matter! Although moving the functions to separate files solved the issue for now, I prefer not to rely on this approach in future projects.

Answer №1

It appears that in your code, you are utilizing

Aspy = spyOn(AB,'A'); 

However, AB is not an instance of a component or class; rather, it is simply a constant used to import these global functions into your spec file.

The issue at hand does not stem from any errors in your testing of "async" functions specifically. Instead, the problem lies in how you are creating spies for your functions without objects related to classes or components. To address this, consider revisiting your approach and exploring alternative solutions outlined in the thread linked below to see if adjusting your spies using one of the provided methods allows your initial tests to execute smoothly.

Using Jasmine to spy on a function without an object

Answer №2

I discovered a solution to effectively mock A within B. All I had to do was include the exports keyword in my function call:

export async function B() {
    exports.A();
}

By doing this, it enables B to access the definition of A and allows the .spec file to recognize that A is referencing the exported method of A.

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

Innovative approaches to enhancing Feathers services through the use of relational data in design patterns

I'm in the process of developing a straightforward application that involves a one-to-many relationship between data entities. Specifically, I am working with feathers js and sequelize (utilizing sqlite) to create a system where each site can have mul ...

Utilizing Typescript generics with an optional second parameter

Learning about generics in typescript has been quite challenging for me. However, I was able to make it work successfully. export type Events = { LOGIN: undefined NAVIGATION: { screen: string } SUPPORT: { communication_method: 'chat&ap ...

Utilizing d3 Charts in Angular 4 Framework

I need assistance with integrating a bar chart in an Angular 4 project, which includes HTML and TypeScript files as components. Can someone please provide guidance on this? The bar chart should show the increase in the number of employees each month, star ...

Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something cruc ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

What is the process for importing a TypeScript module from the local directory?

I am currently working on a TypeScript module with plans to eventually release it on NPM. However, before publishing, I want to import the module into another project hosted locally for testing purposes. Both projects are written in TypeScript. The TypeSc ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

Explain the concept of a static async create method having identical parameters as the constructor

I have a lot of existing classes that require refactoring to utilize an async constructor. Here's an example: class ClassA { constructor(a: number, b: string, c: string) { //... } //... } I've included an async create method ...

Firebase data not appearing on screen despite using the async pipe for observables

My current challenge involves accessing data based on an id from Firebase, which comes back as an observable. Upon logging it to the console, I can confirm that the Observable is present. However, the issue arises when attempting to display this data on th ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

What is the best way to save an array of objects from an Axios response into a React State using TypeScript?

Apologies in advance, as I am working on a professional project and cannot provide specific details. Therefore, I need to describe the situation without revealing actual terms. I am making a GET request to an API that responds in the following format: [0: ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

Accessing the property of an object with TypeScript

I am working with an array of objects, where each object contains two properties: {key:count} When configuring my chart, I need to set the data source in this format: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of ...

Checking the interceptor response in NestJs testing

I created a basic interceptor that removes a specific field from a response: import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } ...

What is the recommended approach in Angular for unassigned @Input() variables when using TypeScript strict mode?

Issue at Hand After upgrading my Angular version from 10 to 13, I encountered a problem with the new TypeScript strict compiler mode. The upgrade required me to assign values to all declared variables upon initialization, causing issues with properties de ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

What are the steps for transforming my 2D array to fit a specific schema using RxJS?

UPDATE I stumbled upon a potential solution that I have appended to my question and am now seeking a more refined approach. In the context of an Angular 9 application, I am working with a two-dimensional array that I need to restructure. Through my use of ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

Custom type declaration file in Typescript fails to function properly

I have searched through countless solutions to a similar issue, but none seem to work for me. I am attempting to utilize an npm package that lacks TypeScript type definitions, so I decided to create my own .d.ts file. However, every time I try, I encounter ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...