Closed EthanML closed 4 years ago
Update: I eventually noticed that CRA projects also have a react-app-env.d.ts
file. It appears that putting import "jest-fetch-mock"
inside this instead of adding a global.d.ts
does in fact work when using require('jest-fetch-mock').enableMocks()
! 🎉
The following syntax also works, so I opted to use it instead as it matched the existing file contents that seem to have been autogenerated by CRA:
// src/react-app-env.d.ts
/// <reference types="jest-fetch-mock" />
I guess I'll leave the original post above for context in case anything useful might come out of this. It does seem like perhaps README instructions are CRA w/ Typescript could be improved. Happy to make those changes if people are satisfied that this ^ is the correct way to go about setting this up?
Spent today attempting to get
jest-fetch-mock
working with a fresh TypeScript CRA app and ran into some issues and general confusion:fetch
orfetchMock
. The line "Fetch will be used as usual by your code and you'll use fetchMock in your tests" from the README implies the latter, but then the examples go on to use justfetch
? What is the actual expected usage here?setupJest
. Guessing this is just leftover from a previous version or a simple typo.Looking at differing recent versions of the README I've seen there have been two different approaches to initializing the library in the test setup file. The currently listed method:
...and the previous suggested method:
First I'll go over issues I had when using
enableMocks()
.fetch
.fetch.mockResponseOnce
.fetch
is referencing the "real"fetch
object:(Ignore the git diff portion, but notice the typing error)
global.d.ts
file withimport "jest-fetch-mock"
inside it as the README suggests however this appears to do nothing.fetchMock
instead offetch
in my tests still allows them to run and pass successfully, but the editor does not know whatfetchMock
is:After some searching I then tried the second approach above involving
GlobalWithFetchMock
.fetch.mockResponseOnce
, however usingfetchMock
now works correctly and has no errors in the editor 🎉I should also state I have only just picked up TS recently and so admittedly I might be missing something very simple here, but it seems to me like the instructions around TS and/or CRA usage with this library may be a little mixed up?
For anyone else struggling with this in the meantime, the test setup approach detailed above appears to be a solution, but it would be nice if the maintainer/s could weigh in on how this is expected to be used.
I did read through https://github.com/jefflau/jest-fetch-mock/issues/82 which made it sound like these issues were resolved however it didn't help. Having looked at that I'm also still confused over whether users are intended to explicitly import
jest-fetch-mock
in their individual test files?