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

问题描述 投票:0回答:1

我有一堆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属性,因为它不是一个函数,而是给出了undefined。

如何访问该类函数?

EDIT.我已经改编了代码,但还是有点麻烦:如何访问那个类函数?

我已经修改了代码,但还是有点问题。

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())
    }
}

服务器.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');

    })

reactjs unit-testing enzyme jest
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")getBy* react-testing-library的函数不是异步的(它们不会返回一个你可以等待解决的承诺),所以你的测试会失败,因为你不会等待一个模拟请求完成。相反,可以尝试 findBy* 这个函数的版本,你可以 await 上,并确保承诺解决。

© www.soinside.com 2019 - 2024. All rights reserved.