I have the following example test:
import { assert } from 'chai'
function starWarsMovies () {
fetch('http://swapi.co/api/films/')
.then((res) => {
return res.json()
})
.then((res) => res.count)
}
describe('Get star war movies', () => {
it('should get 7', () =>{
assert.equal(starWarsMovies(), 7)
})
})
But I getting
ReferenceError: fetch is not defined
What do I have to use in order to test a fetch request.
UPDATE
I also tried:
import { polyfill } from 'es6-promise'
import fetch from 'isomorphic-fetch'
but then I get:
AssertionError: expected undefined to equal 7
and I don't understand why.
You are probably testing your code server-side with node.js.
fetchis not a part of node, but is a web-API, you get with newer browsers and can use from JavaScript running in a browser.You need to import node-fetch as sketched below, and it will work:
and in your code:
If you are running in (an older browser not supporting fetch) and is not using a tool like webpack, you must include the polyfills from your html the old "traditional way".