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

Executing one controller function from another controller in Typescript

There are two typescript controllers in my project Controller A { public methodOfA() {//perform some action} } Controller B { public methodOfB() {//perform some action} } I am trying to implement the following functionality Controller B { ...

Encountering difficulties with a custom Firestore service when attempting to extend it after updating to Angular 9

My custom class that wraps Angular Firestore is designed to be extended and used throughout my application. However, after updating to Angular 9, this setup no longer functions properly. For the complete code snippet, visit . The abstract class wrapper: ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Angular error: "name not found", element is not present in the DOM yet

In my current Angular5 project, I am implementing a small chat system. One issue I encountered is that when a user sends a message, a LI element is dynamically created: chat-component.html <li #ChatListItem *ngFor="let message of messages" class="list ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Angular Toaster Notification - There are currently no toaster containers set up to display notifications

Currently, I am utilizing the angular2-toaster library within my Angular application. It is quite straightforward - you simply define a toaster container in the template of your component: <toaster-container></toaster-container> Then, you ca ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

utilize makeStyles to modify button text color

Initially, my button was styled like this: style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', }}> It worke ...

How can you avoid inspecting webpack internal code when debugging in Visual Studio Code with React Typescript or NextJS?

While debugging NextJS Typescript, the Visual Studio Code debugger seems to be stepping into webpack-internal generated source files. The launch.json file in Visual Studio code is configured as: { "version": "0.2.0", "configura ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Is it possible to apply filters to individual columns in a dynamic mat table using Angular?

Does anyone know how to add a filter for each dynamic column in an Angular Material table? I've only found solutions for static headers, but my table headers are constantly changing. I'm looking for something similar to this example: https://i.st ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Error: The AWS amplify codegen is unable to locate any exported members within the Namespace API

Using AWS resources in my web app, such as a Cognito user pool and an AppSync GraphQL API, requires careful maintenance in a separate project. When modifications are needed, I rely on the amplify command to delete and re-import these resources: $ amplify r ...

Issue encountered in Angular app-routing module.ts: Type error TS2322: The type '"enabled"' cannot be assigned to type 'InitialNavigation | undefined'

When I recently updated my project from Angular 11 to 14, I encountered the following error when running "ng serve". Error: src/app/app-routing.module.ts:107:7 - error TS2322: Type '"enabled"' is not assignable to type 'InitialNavigation | u ...

Struggling with getting Typescript async/await to function properly

I'm experiencing an issue with async/await in TypeScript targeting es2017. Here is the code snippet that's causing trouble: My route.ts : method: 'POST', config: { auth: { strategy: &apo ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...