jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
883 stars 116 forks source link

TypeScript integration not working #110

Closed yordis closed 5 years ago

yordis commented 5 years ago

I am not sure what I am doing wrong since I following the documentation

// setupFiles

import { GlobalWithFetchMock } from 'jest-fetch-mock';

const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock;

customGlobal.fetch = require('jest-fetch-mock');

customGlobal.fetchMock = customGlobal.fetch;

tests

afterEach(() => {
    fetchMock.resetMocks(); // Cannot find name 'fetchMock'
  });

it keeps saying Cannot find name 'fetchMock' TS2304

vspedr commented 5 years ago

@yordis I'm running into the same issue, how did you solve this?

yordis commented 5 years ago

Setup: https://github.com/straw-hat-team/javascript/blob/develop/packages/libraries/fetcher/test/setup-files.ts

import { GlobalWithFetchMock } from 'jest-fetch-mock';

const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock;

customGlobal.fetch = require('jest-fetch-mock');

customGlobal.fetchMock = customGlobal.fetch;

Usage:

https://github.com/straw-hat-team/javascript/blob/e428d750c2223c70c362eccd5a31f1022783234c/packages/libraries/fetcher/test/index.test.ts#L15

https://github.com/straw-hat-team/javascript/blob/e428d750c2223c70c362eccd5a31f1022783234c/packages/libraries/fetcher/test/index.test.ts#L15

afterEach(() => {
    fetchMock.resetMocks();
  });

 expect(fetchMock.mock.calls[0][0].method).toEqual('GET');

I think this stop failing for me, I don't remember.

viT-1 commented 4 years ago

@yordis These links aren't available =(

yordis commented 4 years ago

@viT-1 let me fix it, I am so sorry

viT-1 commented 4 years ago

just found another setup configuration (https://github.com/jefflau/jest-fetch-mock/issues/82#issuecomment-475067797):

in jest setup file: require('jest-fetch-mock').enableMocks();

in test:

import { FetchMock } from 'jest-fetch-mock';
const fetchMock = fetch as FetchMock;
yinzara commented 4 years ago

Your "in test" part isn't actually necessary though it will fix the issue.

As stated in the README, if you have an issue with "fetchMock" not being found, add a "global.d.ts" file at the root of the repository (or next to your tsconfig.json file) with the text import "jest-fetch-mock". That should allow all your tests to reference the "fetchMock" global variable without adding that snippet.

viT-1 commented 4 years ago

@yinzara Quoted from here

"Magically available interfaces" or global types is highly discouraged and should mostly be left to legacy.