question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[jest] Add an example of testing using jest

See original GitHub issue

Hello, could you add some example of testing a component that uses Routify (or its part like url)?

This would improve our experience and avoid struggling with configuration in the future.

For example, I built my project from scratch using npx @roxi/routify@next create my-r3-app, then installed necessary packages (npm i --save-dev jest babel-jest svelte-jester @testing-library/svelte babel). However, still encounter an error - referring to ESM support - like:

ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension 
and '/home/.../svelte/my-r3-app/package.json' contains "type": "module". 
To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

version 3. But also related to the 2

files babel.config.js:

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current"
        }
      }
    ]
  ],
  plugins: ["@babel/plugin-transform-modules-commonjs"]
};

jest.config.js:

module.exports = {
  transform: {
    "^.+\\.svelte$": [
      "svelte-jester",
      {
        "preprocess": true
      }
    ],
    "^.+\\.ts$": "ts-jest",
    "^.+\\.js$": "babel-jest"
  },
  moduleFileExtensions: [
    "js",
    "ts",
    "svelte"
  ]
};

Note: see discussion at the Discord #general channel.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
jakobrosenbergcommented, Nov 27, 2022

Thanks for the solution @cooperwalbrun . I might include a link to your post. 🙂

0reactions
cooperwalbruncommented, Nov 20, 2022

Alright, I did some tinkering with mocking in Jest and I managed to come up with a solution that allows for a little more flexibility in mocked values (thanks @jakobrosenberg for pointing me to your custom framework; it helped guide me to the answer).

Below demonstrates how to mock specific Routify helper functions using Jest such that rendering components which depend on them causes no errors. @jakobrosenberg I am not sure whether you would want to include this example somewhere in the Routify documentation?

import type { Readable, Unsubscriber } from 'svelte/store';
import type { IsActiveHelper, UrlHelper } from '@roxi/routify/typings/runtime/helpers';
import { derived, readable } from 'svelte/store';

const mockIsActive: IsActiveHelper = path => true; // Customize this based on your unit test
const mockUrl: UrlHelper = path => path; // Customize this based on your unit test

function mockAggregator<T>(value: T, setter: (value: T) => void): void | Unsubscriber {
  // Do nothing; there is no reason to aggregate value changes because we hard-code the returned
  // values in mockIsActive and mockUrl above
}

jest.mock('@roxi/routify', () => {
  // These mock store definitions must be defined here (instead of e.g. global scope) because Jest
  // will automatically hoist the jest.mock() call to the top of the file, and if isActiveStore or
  // urlStore were defined in global scope, they would be undefined at the point in time this mock
  // is being invoked.
  // See: https://www.bam.tech/article/fix-jest-mock-cannot-access-before-initialization-error
  const isActiveStore: Readable<IsActiveHelper> = {
    subscribe: (run, invalidate) =>
      derived(readable<IsActiveHelper>(), mockAggregator, mockIsActive).subscribe(run, invalidate)
  };
  const urlStore: Readable<UrlHelper> = {
    subscribe: (run, invalidate) =>
      derived(readable<UrlHelper>(), mockAggregator, mockUrl).subscribe(run, invalidate)
  };

  return {
    // Add other Routify mocks here as needed
    isActive: isActiveStore,
    url: urlStore
  };
});

test('my test', () => {
   // Render your Svelte component(s) as usual
});

Additional Findings

Interestingly, when I tried doing this:

derived(readable(mockIsActive), mockAggregator).subscribe(run, invalidate)

I received internal Svelte errors in my tests. I had expected this derived usage to work the same as

derived(readable(), mockAggregator, mockIsActive).subscribe(run, invalidate)

because the API documentation suggests that these are simply different ways to express the same thing, but that does not appear to be the case. Anyway, this is not an issue in practice because the latter approach works fine - I just wanted to call it out here for awareness.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting Started - Jest
You just successfully wrote your first test using Jest! This test used expect and toBe to test that two values were exactly identical....
Read more >
Jest Tutorial - JavaScript Unit Testing Using Jest Framework
In this Jest tutorial, we will learn about various Jest features, Jest matchers and how to use Jest framework for JavaScript Unit Testing....
Read more >
Jest Tutorial for Beginners: Getting Started With JavaScript ...
Jest is a JavaScript test runner, that is, a JavaScript library for creating, running, and structuring tests. Jest ships as an NPM package,...
Read more >
Jest Testing Tutorial: 5 Easy Steps - Testim Blog
1. Install Jest Globally · 2. Create a Sample Project · 3. Add Jest to the Project · 4. Write Your First Test...
Read more >
How to add Unit Testing to Express using Jest - Fek.io
The testing framework I prefer to use is Jest, but it is not a requirement for unit testing an express application. Jest is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found