testing fetch with mocha and chai

≯℡__Kan透↙ 提交于 2021-01-23 06:50:27

问题


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.


回答1:


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




回答2:


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!



来源:https://stackoverflow.com/questions/41467126/testing-fetch-with-mocha-and-chai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!