npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-jest-mock-import-meta

v1.2.1

Published

A simple Typescript AST transformer for ts-jest, that mock import.meta expressions.

Downloads

322,301

Readme

ts-jest-mock-import-meta AST transformer Npm package version

Install

npm install -D ts-jest-mock-import-meta

:green_book: This transformer is aimed to be used with ts-jest

That moment finally came, where you want to test your esm code that use "import.meta" expressions. (if your are like me, and you do not embrace the TDD approach :smirk:). You type "jest" in the console, and this infamous error pops up :

> jest

 FAIL  src/anyfile.spec.ts
  ● Test suite failed to run

    src/anyfile.spec.ts:2:24 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.

    2   const url = new URL('./', import.meta.url) !== undefined;
                             ~~~~~~~~~~~

Worry not !

Here comes this simple typescript AST transformer to the rescue. By using it "before" typescript transpilation, it will simply replace any "import.meta" expressions in typescript files by a mocked object. "import.meta" expressions are not compatible with jest, that by default, works in commonjs, so they need to be stripped down and replaced by a mocked object before typescript transpilation is done by ts-jest.

Configuration examples (jest.config) :

📘 See ts-jest options documentation for more details about configuration : https://kulshekhar.github.io/ts-jest/docs/getting-started/options

ℹ️ Options structure changed since ts-jest 29.0.0. Make sure to check the example that corresponds to the version of ts-jest you are using.

⚠️ IMPORTANT: error code 1343 MUST be ignored for the transformer to work. https://github.com/Microsoft/TypeScript/blob/main/src/compiler/diagnosticMessages.json#L1035

{
  // [...]
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        diagnostics: {
          ignoreCodes: [1343]
        },
        astTransformers: {
          before: [
            {
              path: 'node_modules/ts-jest-mock-import-meta',  // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules.
              options: { metaObjectReplacement: { url: 'https://www.url.com' } }
            }
          ]
        }
      }
    ]
  }
}
{
  // [...]
  globals: {
    'ts-jest': {
      diagnostics: {
        ignoreCodes: [1343]
      },
      astTransformers: {
        before: [
          {
            path: 'node_modules/ts-jest-mock-import-meta',  // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules.
            options: { metaObjectReplacement: { url: 'https://www.url.com' } }
          }
        ]
      }
    }
  }
}

Options

  • [metaObjectReplacement] (Optional):

    The mock object or factory function that (the returned value for the latter) will override all "import.meta" expressions. Note that the factory function and all function properties will be called with the replacement context as an argument, and it will always be the returned value that will be used.

    [Type] Record<string, any> or (ctx: ReplacementContext) => Record<string, any>

    /** @type {ReplacementContext} */
    { 
      fileName: string 
    }

    [Default Value]

    { url: ({ fileName }) => `file://${fileName}` };

    [Example Values]

    // An object
    {
      url: 'https://www.url.com',
      env: {
        PROD: false,
        DEV: true
      },
      status: 2,
      file: ({fileName}) => fileName
    }
    // A factory function
    ({ fileName }) => ({
      url: fileName,
      env: {
        PROD: false,
        DEV: true
      },
      status: 2
    })

If you found this project helpful, please consider giving it a ⭐! Your support means a lot and helps others discover this repository too.