What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module.

index.svelte

import {url} from '@roxi/routify';

someFunction(() => {
  let x = $url('/books') // this line needs to be mocked
  console.log('x: ' + x);
});

Is there a way I can mock this specific line of code?

$url("/books")

$ prefix

Additional Details:

url() is an object containing the named function subscribe(listener)

subscribe(listener) invokes the function derived(...), which in turn returns a Readable interface

The Readable interface has its own subscribe(...) function

Attempts made so far:

#1 Tried using mockReturnValue for subscribe within url

import {readable} from "svelte/store";
import {mocked} from "jest-mock";
import {render} from "@testing-library/svelte";
import * as routify from "@roxi/routify";
import books_index from "./index.svelte";

jest.mock("@roxi/routify", jest.fn(() => {
  return {
    __esModule: true,
    url: {
      subscribe: jest.fn().mockReturnValue(readable())
    }
  }
}));

const mockedRoutify = mocked(routify);

it("needs to work", () => {
  const results = render(books_index);
  expect(results);
});

This resulted in:

ReferenceError: Cannot access 'store_1' before initialization

#2 Attempted another approach with mockReturnValue for subscribe within url

jest.mock("@roxi/routify", jest.fn(() => {
  return {
    __esModule: true,
    url: {
      subscribe: jest.fn().mockReturnValue(() => readable())
    }
  }
}));

This led to:

TypeError: $url is not a function

Other notes to consider:

  • Attempted a different strategy within the test, resulting in

    routify_1.url.mockReturnValue is not a function

  • Tried both with and without __esModules: true.

  • Played around with the placement of imports and mock declarations.

  • Another test involving a custom service is functioning correctly, indicating that my jest.config.ts and tsconfig.json are set up properly.

Request for Assistance:

What crucial element am I overlooking in this process?

Answer №1

Although Svelte is not my area of expertise, I would suggest mocking it like this:

import * as routify from "@roxi/routify";

//you have the flexibility to return any desired value in this mocked function
jest.spy(routify, 'url').mockReturnValue({
   subscribe: jest.fn()
}) 

It's important to note that by doing this, you are essentially overriding the original function (url). This means that only the subscribe attribute/function will be available in the mocked url.

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

Optimizing Performance in Firebase Cloud Functions - Defining Functions for Efficiency

Currently, I am organizing the code in my index.ts by creating simple line function definitions like: HTTP Example export const demoHttpApp = functions.https.onRequest( (req, resp) => new DemoHttpClass(req, resp).run() ); Real-Time Database Example ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

Rendering a React/Material UI class based on the state variable in a conditional manner

I am currently working on building a basic navbar setup using React and Material UI. I have encountered an issue where React-Router-Dom does not seem to be functioning within this particular project, and implementing it would be excessive for the simple ta ...

Struggling to make Mongoose with discriminator function properly

I seem to be facing an issue with my schema setup. I have defined a base/parent Schema and 3 children schemas, but I am encountering an error message that says: No overload match this call Below is the structure of my schema: import { model, Schema } fr ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

When interacting with a <select> element, the behavior of test script execution varies between Firefox and Chrome

I've encountered an unusual problem that I need help describing and solving. Your assistance is greatly appreciated! The issue I'm facing involves Testcafe behaving differently when running the same test script on various browsers. testcafe: ...

Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation availab ...

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

The Vue Prop does not have an initializer and is not explicitly assigned in the constructor

Currently, I am utilizing props in Vue Class components. Within the constructor, I have defined the props without a value. This setup compiles and operates smoothly, except after the most recent VS Code / TSLint update, a warning message emerges: The pr ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...

Guide on how to include jquery-ui css file in Vue3

I am new to TypeScript and VueJs. Recently, I decided to incorporate jquery-ui into my project using Vue3, TypeScript, and Electron. After some trial and error, I was able to successfully set up the environment. However, when I attempted to use the jquery ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Creating an Http Service Instance in Angular 2 by Hand

Can the Http Service be initialized manually without needing it as a constructor argument? export class SimpleGridServer { private http: Http; constructor(public options: SimpleServerData) { http = new Http(.../* Argument here */); } } ...

Creating comprehensive and elaborate intellisense documentation for Typescript Union Types

When we call the baz function with the code provided, the typeahead will display 'a' and 'b' as potential values. https://i.stack.imgur.com/SrKo7.png If additional documentation is needed for each of these values, how can it be accomp ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

The Intersection of Material-UI, TypeScript, and Powerful Autocomplete Features

In my TypeScript project, I'm attempting to develop a Material-UI AutoComplete component that retrieves the input value based on an object's property name -> obj[key] However, when using the prop getOptionLabel, I encountered the following er ...

Element not producing output via Autocomplete from mui/material package

My challenge involves handling an array of states within the Autocomplete component. Once a state is selected, a corresponding component needs to be rendered based on the selection. However, despite successful state selection in the code, nothing is being ...

The concept of recursive generics in combination with array inference

I'm struggling to develop a couple of generic recursive types to adjust the structure of existing types. I can't figure out why the sections detecting arrays and nested objects are not being activated. Any thoughts on what might be going wrong? ...