用摩卡和柴测试获取 [英] testing fetch with mocha and chai

查看:38
本文介绍了用摩卡和柴测试获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例测试:

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.js在服务器端进行测试.

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

获取不是节点的一部分,而是一个Web-API,您可以通过较新的浏览器获得它,并且可以在运行在浏览器中的JavaScript中使用.

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.

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

You need to import node-fetch as sketched below, and it will work:

npm install node-fetch --save

并在您的代码中:

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

如果您正在运行(较旧的浏览器不支持提取),并且未使用webpack之类的工具,则必须以旧的传统方式"包含html中的polyfill.

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

这篇关于用摩卡和柴测试获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆