testing fetch with mocha and chai

7.4k views Asked by At

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.

2

There are 2 answers

0
Ryan Volum On

Even if you use node-fetch or isomorphic-fetch the issue here is that you're checking for equality between a number and the result of a function that doesn't return anything. I was able to make this work!

describe('Get star war movies', () => {
    it('should get 7', async () => {
        await fetch('http://swapi.co/api/films/')
            .then((res) => {
                return res.json()
            })
            .then((res) => {
                console.log(res);
                assert.equal(res.count, 7)
            })
    })
})

Note that I'm using async await syntax here. There are lots of different ways we could do this (callbacks, promises, async/await), but the key is that in making a call out to an API we have to wait for the result. Also, the response you get from the star wars API seems to be a huge object, so I took the liberty of assuming that you were just checking for the count!

0
Plaul On

You are probably testing your code server-side with node.js.

fetch is 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:

npm install node-fetch --save

and in your code:

const fetch = require("node-fetch")
...

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".