Ошибка при тестировании fetch в vanilla JavaScript с помощью jest-fetch-mock - PullRequest
0 голосов
/ 29 декабря 2018

Я пытаюсь проверить выборку из класса.Мне нужно создать экземпляр класса для доступа к методу выборки.Если я исключу класс и вернусь напрямую, метод сработает.

Я попытался выполнить тест таким образом, но он возвращает неопределенное значение.Любое решение?

Большое спасибо

//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

Я получил:

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 тоже не определено.Я делаю что-то не так, но я не знаю, что это такое.

1 Ответ

0 голосов
/ 01 января 2019

Я вижу две проблемы, которые вы можете исправить, чтобы все заработало.

Первая состоит в том, что, поскольку getSections является асинхронной функцией (она возвращает обещание), вам нужно вызывать ее асинхронно из своего теста,Ваш метод тестирования уже помечен как async, поэтому все, что вам нужно сделать, это добавить ключевое слово await перед вызовом.

const res = await request.getSections()

Во-вторых, ваш код Request ожидает ответа сервера, которыйвключает в себя sections свойство, которого нет у вашего макета.Попробуйте изменить макет, чтобы он включал свойство sections, например:

fetch.mockResponseOnce(JSON.stringify({ sections: { data: "12345" }}));

Если вы сделаете эти два изменения, ваш тест должен пройти.

...