samedi 20 octobre 2018

How does mocking API calls ensure our app runs correctly

I'm currently going through Testing React Applications with Jest from Daniel Stern and I've finally hit the portion where I'm learning to mock API calls. What I'm wondering is if I'm literally telling the mock what to return, how is this supposed to make me feel confident in that my actual production code is going to work?

For example, in the course he's using some call from redux-saga so I decided to replicate this with axios as I am more familiar with axios.

__mocks__/axios.js

let __value;

const axios = jest.fn(() => __value)

axios.__fetch = value => {
  console.log(value)
  return __value = value
}

export default axios

src/helpers/fetch.js

import axios from 'axios'

export async function testFetch(id) {
  const data = await axios(`https://jsonplaceholder.typicode.com/todos/${ id }`)
  console.log(data)
  return data
}

src/helpers/fetch.test.js

import axios from 'axios' // this is the mock version
import testFetch from './fetch'

describe('testFetch', () => {
  beforeAll(() => {
    axios.__fetch({ userId: 1, id: 1, title: "delectus aut autem", completed: false })
  })

  it('should fetch correct list of todos', async () => {
    const todo = await testFetch(1)

    expect(todo).toEqual({ userId: 1, id: 1, title: "delectus aut autem", completed: false })
expect(axios).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/todos/1')
  })
})

Sure this comes back correct but I don't feel confident in the code. What's the point of doing things this way when it's not actually making the call? What happens if the API changes, now my tests continue to return correct but my app doesn't making it difficult to debug the app, which is defeating the purpose of these tests right?

Lastly, should I consider making REAL calls to the API and if so how would I go about testing a real one?

Aucun commentaire:

Enregistrer un commentaire