How do I mock a function inside an object with Jest & Typescript?

Viewed 842

I have a function that will make a call to url

index.svelte

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

someFunction(() => {
  let x = $url('/books') // need to mock this call
  console.log('x: ' + x);
});

How can I mock this line of code?

$url("/books")

$ prefix

Details:

url() is an object that declares a named function subscribe(listener)

subscribe(listener) makes a call to the function derived(...), which returns a Readable interface

Readable interface declares a different subscribe(...) function

What I have tried:

#1 mockReturnValue from subscribe inside 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);
});

Results in: ReferenceError: Cannot access 'store_1' before initialization

#2 mockReturnValue from subscribe inside url

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

Results in: TypeError: $url is not a function

Other notes

  • I have tried inside the test, but then I get routify_1.url.mockReturnValue is not a function

  • I have tried it with __esModules: true & without it.

  • I have tried playing around with where the imports & mock declarations are made.

  • I do have another test with my own service working, so I am confident that my jest.config.ts and tsconfig.json is correct.

Ask

What am I missing?

1 Answers

I'm not familiar with Svelte, but I guess you should mock this way

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

//you can return whatever you want in this mocked function
jest.spy(routify, 'url').mockReturnValue({
   subscribe: jest.fn()
}) 

One thing you need to keep in mind. This one will help you to override the original function (in this case, it's url) which means you won't have other attributes/functions in url except subscribe

Related