首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jest- fetch -mock测试普通JavaScript中的fetch时出错

使用jest- fetch -mock测试普通JavaScript中的fetch时出错
EN

Stack Overflow用户
提问于 2018-12-29 19:57:38
回答 1查看 3K关注 0票数 2

我正在尝试测试一个类的抓取。我需要创建一个类实例来访问fetch方法。如果我去掉这个类并直接返回,这个方法就可以工作了。

我尝试以这种方式进行测试,但它返回未定义。有什么解决方案吗?

非常感谢

代码语言:javascript
复制
//api.test.js
//import the class Request and module jest-fetch-mock
import Request from './index'
global.fetch = require('jest-fetch-mock')

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('calls api and returns data to me', async () => {
    const request = new Request('http://localhost:3000/api.json')
    fetch.mockResponseOnce(JSON.stringify({data: '12345'}))

    // assert on the response
    const res = request.getSections()
    expect(res.data).toEqual('12345')


    // assert on the times called and arguments given to fetch
    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('http://localhost:3000/api.json')
  })
})

//api.js
/**
* Request Component
* @class Request
*/
class Request {
/**
* Creates an instance of Request
*
* @param {String}  url - The url of the API
* @throws {Error} - Incorrect type
* @memberof Request
*/
  constructor(url) {
     if (typeof url !== 'string') throw TypeError(`${url} is not a string`)
     this.url = url
  }

  /**
  * Handler get sections from api
  * @memberof Request
  */
  getSections() {
     return fetch(this.url)// eslint-disable-line
       .then(res => res.json())
       .then(result => result.sections)
       .catch(err => console.error(err)) // eslint-disable-line
  }
}

export default Request

我收到了:

代码语言:javascript
复制
expect(received).toEqual(expected)

Expected value to equal:
  "12345"
Received:
  undefined

Difference:

  Comparing two different types of values. Expected string but received undefined.

  14 |     // assert on the response
  15 |     const res = request.getSections()
> 16 |     expect(res.data).toEqual('12345')
     |                      ^
  17 |
  18 |
  19 |     // assert on the times called and arguments given to fetch

Res也是未定义的。我做错了什么,但我不知道是什么。

EN

回答 1

Stack Overflow用户

发布于 2019-01-01 05:38:34

我认为有两个问题可以解决,以使其正常工作。

首先,因为getSections是一个异步函数(它返回一个promise),所以您需要在测试中异步调用它。您的测试方法已经标记为async,因此只需在调用前添加await关键字即可。

代码语言:javascript
复制
const res = await request.getSections()

其次,您的Request代码期望得到一个包含sections属性的服务器响应,而您的模拟没有该属性。尝试更改您的模拟以包含sections属性,例如:

代码语言:javascript
复制
fetch.mockResponseOnce(JSON.stringify({ sections: { data: "12345" }}));

如果您进行了这两个更改,您的测试应该会通过。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53969291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档