Testing extension method with ts-jest

58 Views Asked by At

I created an extension method for luxon's DateTime class:

import { DateTime } from "luxon";

declare module "luxon/src/datetime" {
  export interface DateTime {
    myFunction(month: number): DateTime;
  }
}

DateTime.prototype.quarterStart = function (month: number): DateTime {
  
  const result = DateTime.fromObject({
    day: 1,
    month: month,
    year: year,
  });

  return result;
};

The method implementation is not what's important, it will be something else.

Then on my tests I have:

describe("DateTime extensions", () => {
  it.each<number>([1,2,3,4])("call quarterStart  function", (month) => {
    const testDate = DateTime.fromObject({ year: 2023, month: 5,day: 1 });

    const start = DateTime.fromObject({ year: 2023, month: month, day: 1 });;
    const expected = testDate.quarterStart(month);
    expect(start).toBe(expected);
  });
});

I don't get any errors if I try to build the code, but if run the tests it fails with this message:

TypeError: testDate.quarterStart is not a function

I've tried this solution but nothing works.

I haven't been able to find any other info online.

Am I missing something on the extension side, jest config, or both?

1

There are 1 best solutions below

0
On

Test could not find your extension method at runtime. You need to import 'luxon/src/datetime' into your test file.

import 'luxon/src/datetime';

describe("DateTime extensions", () => {
  it.each<number>([1,2,3,4])("call quarterStart  function", (month) => {
    const testDate = DateTime.fromObject({ year: 2023, month: 5,day: 1 });

    const start = DateTime.fromObject({ year: 2023, month: month, day: 1 });;
    const expected = testDate.quarterStart(month);
    expect(start).toBe(expected);
  });
});