【问题标题】:testing fetch with mocha and chai用 mocha 和 chai 测试 fetch
【发布时间】:2017-01-04 15:14:11
【问题描述】:

我有以下示例测试:

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

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

更新


我也试过了:

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

然后我得到:

AssertionError: expected undefined to equal 7

我不明白为什么。

【问题讨论】:

标签: javascript testing mocha.js fetch-api chai


【解决方案1】:

您可能正在使用 node.js 测试您的代码服务器端。

fetch 不是 node 的一部分,而是一个 web-API,您可以通过较新的浏览器获得,并且可以从运行在浏览器中的 JavaScript 使用。

您需要导入node-fetch,如下图所示,它会起作用:

npm install node-fetch --save

在你的代码中:

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

如果您正在运行(不支持 fetch 的旧浏览器)并且没有使用 webpack 之类的工具,则必须以旧的“传统方式”包含来自 html 的 polyfill。

【讨论】:

    【解决方案2】:

    即使您使用node-fetch 或isomorphic-fetch,这里的问题是您正在检查数字与不返回任何内容的函数结果之间的相等性。我能够完成这项工作!

    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 获得的响应似乎是一个巨大的对象,所以我冒昧地假设您只是在检查计数!

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 2015-12-01
      • 2013-04-11
      • 1970-01-01
      • 2017-02-18
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多