Unfinished snippets utilizing Jest and TypeScript

While attempting to stub out a function for testing with Jest, I encountered an issue due to TypeScript's insistence on returning all object fields in the stub. However, I only need two specific fields and the object is quite complex.

The Initial Setup

import * as sinon from "sinon";
import * as stripeHelpers from "../../src/lib/stripe";

describe("lib/authorization", () => {
    let sandbox: sinon.SinonSandbox;
    beforeAll(() => {
        sandbox = sinon.createSandbox();
    });

    afterEach(() => {
        sandbox.restore();
    });

    describe("getAuthorizationDateRange", () => {
        test("returns an authorization date range", async () => {
            const getUserSubscriptionStub = sandbox.stub(stripeHelpers, "getUserSubscription").resolves({
                current_period_end: 123123,
                current_period_start: 123123
            });
        });
    });
});

My Objective

import * as sinon from "sinon";
import * as stripeHelpers from "../../src/lib/stripe";

describe("lib/authorization", () => {
    let sandbox: sinon.SinonSandbox;
    beforeAll(() => {
        sandbox = sinon.createSandbox();
    });

    afterEach(() => {
        sandbox.restore();
    });

    describe("getAuthorizationDateRange", () => {
        test("returns an authorization date range", async () => {
            const getUserSubscriptionStub = sandbox.stub(stripeHelpers, "getUserSubscription").resolves({
                current_period_end: 123123,
                current_period_start: 123123
            });
        });
    });
});

Function Under Test

export async function getAuthorizationDateRange(user: User): Promise<DateRange> {
    const subscription: Stripe.subscriptions.ISubscription = await stripeHelpers.getUserSubscription(user);
    return {
        start: moment.unix(subscription.current_period_start).toDate(),
        end: moment.unix(subscription.current_period_end).toDate()
    };
}

Given that the function only requires the first two properties, it seems unnecessary to replicate the entire complex object. The

Stripe.subscriptions.ISubscription
interface includes intricate nesting that I prefer avoiding in my tests.

Answer №1

The solution is simply to explicitly typecast the object as any.

const getUserSubscriptionStub = sandbox.stub(stripeHelpers, "getUserSubscription").resolves({
    current_period_end: 123123,
    current_period_start: 123123,
} as any);

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

How to Manage API Requests in React Native?

I am in the process of familiarizing myself with react native and attempting to communicate with an API helper that I have implemented within one of my screen files. While I suspect there may be a syntax error causing issues, I also wonder about the overal ...

Angular: Rendering an array of objects that include nested arrays

Can someone help me figure out how to display this array of objects in Angular? var list = [{ collaborators: [{ id: 1, name: "test" }] }, { colleagues: [{ id: 2, name: "colleague2" }] } ] I ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

Zod Schema consolidates an array of objects into a single, comprehensive object

I have been working with a couple of schemas, where one contains an array of the other as a value. For example, const ActionSchema = {id: z.string(), name: z.string(), description: z.string()} const PersonSchema = { id: z.string(), actions: ActionSchema.a ...

Ways to update the value of an object in typescript

When working with an array of objects, I encountered an issue while trying to change the object value. The error message "Type 'string | boolean' is not assignable to type 'never'. Type 'string' is not assignable to type &apos ...

Typing function parameters that accept generic types "from the identical instance"

I have come across a similar implementation of an Event Emitter in TypeScript and I am looking to create a helper function that maintains type integrity. You can find my code attempt on TS Play sample page. Below is the snippet from my sample: In the prov ...

Extract information from checkboxes within a form

Having an issue with retrieving data from a form submission in Angular. The goal is to receive the user-submitted data wrapped in a single object, utilizing formBuilder. However, it seems that formBuilder only works well with <input> tags, as mention ...

Issue with test and images in Ionic 2

When attempting to test my Ionic 2 app using Jasmine and Karma, I encountered an error after running 'npm test': C:\xampp\htdocs\MyApp>npm test > ionic-hello-world@ test C:\xampp\htdocs\MyApp > karma start ...

How do you implement radio button logic within an *ngFor loop?

When I populate options in a form with radio buttons, I am not seeing isChecked set to true when I select an option. Am I missing something in the following Angular code? app.component.html <div class="form-group"> <label>answerOption</la ...

What is the best way to prioritize the display of custom login buttons based on the last button used for login?

I have implemented 4 different login methods for my app, each with its own associated component. I am looking to rearrange the buttons based on the last used login method. I already have a function to determine the last login method. let lastSignedInMetho ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

What is the best way to implement generics for a zip function in TypeScript?

I want to enhance this JS function by including types: function zip(array1, array2) { const length = Math.min(array1.length, array2.length); const result = []; for (let i = 0; i < length; i++) { result.push([array1[i], array2[i]]); } retur ...

React component not accurately substituting function with Sinon stub

I'm currently experimenting with testing a click on a React component using Enzyme and Sinon. var stub = sinon.stub(Comp.prototype, 'save', function() { }); let wrapper = shallow( <Comp/> ); wrapper.find('.btn-header' ...

Changing namespaces or module containers that share the same name can result in a clash

Trying to reorganize some code that was mistakenly namespaced and move it to its own namespace without affecting the current functionality during the process. The original code is structured as follows: // (org) module General.Admin.Dialogs { export cl ...

Retrieving the Value of a Member in an Object using Angular

Is there a way to retrieve the value of an object in Angular using a variable as the member identifier? For example: --> my Angular class object: Object1 { name: foo property2: bar } --> my function: myFunction(memberName: string) { return Ob ...

The Problem with TypeScript Union Types

I recently started using TypeScript and ran into an issue with a similar scenario. Despite my efforts, I encountered two errors that I can't seem to figure out. If anyone has any insights on how to resolve this, I would greatly appreciate the help! in ...

Updating a separate component in Next.js upon the deletion of an item from the Supabase database

I am facing an issue with updating my parent component after deleting an item from the database. To fetch items from the database, I use a simple approach: const filter = useFilter((query) => query.eq("createDate", date), [date]); const [{ ...

Mocking functions using Sinon and Asynchronous calls

I am working on a project where I have a file called mainFile that utilizes a method named helperMethod. This method, which resides in a separate file called helperFile, returns a Promise. How can I mock the output of the helperMethod? Here is the structu ...

Uncertainty regarding the integration process of `create-react-app --template typescript` with typescript-eslint

After creating a react project using npx create-react-app my-app --template typescript, I was surprised to find that typescript-eslint was already enabled by default. https://i.sstatic.net/1uijf.png Upon inspecting the eslint config within the package.jso ...