用 mocha 和 chai 测试 fetch

2022-01-20 00:00:00 testing fetch javascript chai mocha.js

我有以下示例测试:

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)
  })
})

但我得到了

ReferenceError: fetch is not defined

我必须使用什么来测试获取请求.

What do I have to use in order to test a fetch request.

更新

我也试过了:

import { polyfill } from 'es6-promise'
import fetch from 'isomorphic-fetch'

然后我得到:

AssertionError: expected undefined to equal 7

我不明白为什么.

推荐答案

即使你使用 node-fetch 或 isomorphic-fetch 这里的问题是您正在检查一个数字和一个不返回任何东西的函数的结果之间的相等性.我能够完成这项工作!

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)
            })
    })
})

请注意,我在这里使用异步等待语法.有很多不同的方法我们可以做到这一点(回调、承诺、异步/等待),但关键是在调用 API 时,我们必须等待结果.此外,您从星球大战 API 获得的响应似乎是一个巨大的对象,所以我冒昧地假设您只是在检查计数!

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!

相关文章