Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Last active March 5, 2024 13:07
Show Gist options
  • Save iRoachie/3f9b4855ee4891050c8e900ed9953773 to your computer and use it in GitHub Desktop.
Save iRoachie/3f9b4855ee4891050c8e900ed9953773 to your computer and use it in GitHub Desktop.
Mocking node modules using typescript
import { mocked } from 'ts-jest/utils';
import fetch, { Response } from 'node-fetch';
import { test } from './index';
jest.mock('node-fetch');
it('It works', async () => {
console.log = jest.fn();
mocked(fetch).mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve({ results: [{ name: { first: 'Bob' } }] }),
} as Response)
);
await test();
expect(console.log).toHaveBeenCalledWith('Hello Bob');
});
import fetch from 'node-fetch'
export async function test() {
const result = await fetch('https://randomuser.me/api/');
const data = await result.json()
console.log(`Hello ${data.results[0].name.first}`)
}
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
{
"name": "ts-test",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@types/jest": "^25.2.1",
"@types/node-fetch": "^2.5.7",
"jest": "^25.5.3",
"ts-jest": "^25.4.0",
"ts-node": "^8.9.1",
"typescript": "^3.8.3"
},
"dependencies": {
"node-fetch": "^2.6.0"
},
"scripts": {
"test": "jest"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment