React-如何在Jest中对API调用进行单元测试?

时间:2020-05-03 14:50:06

标签: reactjs unit-testing jestjs enzyme

我有很多我想进行单元测试的API调用。据我所知,单元测试API调用实际上并不涉及进行这些API调用。据我所知,您将模拟这些API调用的响应,然后对DOM更改进行测试,但是我目前仍在努力做到这一点。我有以下代码:

App.js

function App() {

  const [text, setText] = useState("");

  function getApiData() {
        fetch('/api')
        .then(res => res.json())
        .then((result) => {
          console.log(JSON.stringify(result));
          setText(result); 
        })
      }

  return (
    <div className="App">
      {/* <button data-testid="modalButton" onClick={() => modalAlter(true)}>Show modal</button> */}
      <button data-testid="apiCall" onClick={() => getApiData()}>Make API call</button>
      <p data-testid="ptag">{text}</p>
    </div>
  );
}

export default App;

App.test.js

it('expect api call to change ptag', async () => {
  const fakeUserResponse = {'data': 'response'};
  var {getByTestId} = render(<App />)
  var apiFunc = jest.spyOn(global, 'getApiData').mockImplementationOnce(() => {
    return Promise.resolve({
      json: () => Promise.resolve(fakeUserResponse)
    })
  })


  fireEvent.click(getByTestId("apiCall"))
  const text = await getByTestId("ptag")
  expect(text).toHaveTextContent(fakeUserResponse['data'])
})

我试图在此处模拟getApiData()的结果,然后测试DOM的更改(p标记更改为结果)。上面的代码给了我错误:

因为它不是函数,所以无法监视getApiData属性;未给定

如何访问该类函数?

编辑:

我已经修改了代码,但仍然遇到一些麻烦:

App.js

function App() {

  const [text, setText] = useState("");

  async function getApiData() {
        let result = await API.apiCall()
        console.log("in react side " + result)
        setText(result['data'])
      }

  return (
    <div className="App">
      {/* <button data-testid="modalButton" onClick={() => modalAlter(true)}>Show modal</button> */}
      <button data-testid="apiCall" onClick={() => getApiData()}>Make API call</button>
      <p data-testid="ptag">{text}</p>
    </div>
  );
}

export default App;

apiController.js

export const API = {
    apiCall() {
        return fetch('/api')
        .then(res => res.json())
    }
}

Server.js

const express = require('express')
const app = express()
const https = require('https')
const port = 5000

app.get('/api', (request, res) => {
    res.json("response")
})

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

App.test.js

import React from 'react';
import { render, shallow, fireEvent } from '@testing-library/react';
import App from './App';
import {API} from './apiController'
//import shallow from 'enzyme'

it('api call returns a string', async () => {
  const fakeUserResponse = {'data': 'response'};
  var apiFunc = jest.spyOn(API, 'apiCall').mockImplementationOnce(() => {
    return Promise.resolve({
      json: () => Promise.resolve(fakeUserResponse)
    })
  })
  var {getByTestId, findByTestId} = render(<App />)
  fireEvent.click(getByTestId("apiCall"))
  expect(await findByTestId("ptag")).toHaveTextContent('response');
})

我得到的错误是

expect(element).toHaveTextContent()

   Expected element to have text content:
     response
   Received:

     14 |   var {getByTestId, findByTestId} = render(<App />)
     15 |   fireEvent.click(getByTestId("apiCall"))
   > 16 |   expect(await findByTestId("ptag")).toHaveTextContent('response');
        |                                      ^
     17 | })
     18 | 
     19 | // it('api call returns a string', async () => {

可重复使用的单元测试(希望如此):

    it('api call returns a string', async () => {
      const test1 = {'data': 'response'};
       const test2 = {'data': 'wrong'}

      var apiFunc = (response) => jest.spyOn(API, 'apiCall').mockImplementation(() => {
        console.log("the response " + JSON.stringify(response))
        return Promise.resolve(response)
        })

      var {getByTestId, findByTestId} = render(<App />)

      let a = await apiFunc(test1);
      fireEvent.click(getByTestId("apiCall"))
      expect(await findByTestId("ptag")).toHaveTextContent('response');
      let b = await apiFunc(test2);
      fireEvent.click(getByTestId("apiCall"))
      expect(await findByTestId("ptag")).toHaveTextContent('wrong');

    })

2 个答案:

答案 0 :(得分:3)

不要嘲笑 API 库。最好是存根服务器响应。如果您编写了一堆模拟 API 调用的测试,那么您将应用程序的实现绑定到您的测试。假设您不想使用 fetch(),但想将 isomorphic-unfetch 之类的东西用于 SSR 应用程序?切换整个模拟测试套件将非常痛苦。

相反,使用服务器存根库,如 nockmsw。将这些库视为 JSDOM,但用于您的服务器。通过这种方式,您将测试套件绑定到后端而不是实现库。让我们重写您的示例以向您展示我的意思:

import React from 'react';
import nock from 'nock';
import { render, shallow, fireEvent } from '@testing-library/react';

import App from './App';

it('displays user data', async () => {
  const scope = nock('https://yoursite.com')
    .get('/api')
    .once()
    .reply(200, {
      data: 'response',
    });

  var {getByTestId, findByTestId} = render(<App />)
  fireEvent.click(getByTestId("apiCall"))
  expect(await findByTestId("ptag")).toHaveTextContent('response');
})

查看我写的博客文章,以深入了解该主题,Testing components that make API calls

答案 1 :(得分:0)

您无法访问getApiData,因为它是其他函数(闭包)内部的私有函数,并且不暴露于全局范围。这意味着global变量不具有属性getApiData,并且您将获得undefined given instead

要执行此操作,您需要以某种方式导出此函数,我建议将其移至其他文件,但同样也可以。这是一个简单的示例:

export const API = {
  getData() {
    return fetch('/api').then(res => res.json())
  }
}

组件中的某处:

API.getData().then(result => setText(result))

在测试中:

var apiFunc = jest.spyOn(API, 'getData').mockImplementationOnce(() => {
    return Promise.resolve({
      json: () => Promise.resolve(fakeUserResponse)
    })
  })

还有其他方法可以实现这一目标,但是也许这已经足够了。

我认为还会有另外一个问题。您正在使用const text = await getByTestId("ptag"),但是react-testing-library中的getBy*函数不是异步的(它们不返回可以等待解决的Promise),因此您的测试将失败,因为您不会等待模拟请求完成。相反,请尝试使用await版本的findBy*版本的功能,并确保已兑现承诺。