How to import nock in TypeScript
See original GitHub issueJust a note for anyone googling this (I had a hard time…):
This syntax is used in DefinitelyTyped tests:
import nock = require('nock');
However, it doesn’t work with Babel (in our case, Jest uses Babel under the covers):
SyntaxError: example.ts: `import =` is not supported by @babel/plugin-transform-typescript
Please consider using `import <moduleName> from '<moduleName>';` alongside Typescript's --allowSyntheticDefaultImports option.
This is the recommended syntax:
import nock from 'nock';
But that yielded another error when starting the app via ts-node:
example.ts:7
const mockApi = nock('https://example.com');
^
TypeError: nock_1.default is not a function
It started working when I added "esModuleInterop": true
to tsconfig.json
.
Summary:
- Use
import nock from 'nock'
- Add
"esModuleInterop": true
totsconfig.json
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:7 (3 by maintainers)
Top Results From Across the Web
nock - npm
Start using nock in your project by running `npm i nock`. There are 985 other projects in the npm registry using nock.
Read more >Using mocks when unit testing your TypeScript code
First, make sure to run npm i nock so you can use nock. import nock from 'nock'; import { getItemFromTable } from ...
Read more >API mock testing with Nock for Node.js apps - LogRocket Blog
Install Nock with the following command. ... A simple Nock mocking object looks something like this: import nock from "nock"; const scope =...
Read more >node.js - Nock unexpected Token being caused by typescript?
When I run the ts file on its own everything's fine, but if I run it from inside of mocha I get that...
Read more >Mocking axios in Jest tests with Typescript - C.S. Rhymes
I started by following the example in the article and added jest.mock('axios'); after the imports. Then as per the example, I added the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
import nock from "nock"
is importing a default export, which nock doesn’t provide.It’s true that I’m fighting with this because of how Babel + TypeScript play together but it’s a significant enough stack & the change for Nock would be small so I think it would be worth it.
… and to extend on @borekb summary:
"esModuleInterop": true
should be the go to for any TS app especially for an new app. If, however, you have an existing codebase where turning onesModuleInterop
would be a pain, the alternative is to import using:import * as nock from "nock";
to get the same results.