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.