Last active
March 5, 2024 13:07
-
-
Save iRoachie/3f9b4855ee4891050c8e900ed9953773 to your computer and use it in GitHub Desktop.
Mocking node modules using typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
preset: 'ts-jest', | |
testEnvironment: 'node', | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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