【问题标题】:React Js API call Jest Test Case?React Js API 调用 Jest 测试用例?
【发布时间】:2021-10-16 15:52:48
【问题描述】:

我正在尝试为我的API调用函数编写测试用例,我不知道我无法成功运行测试的错误在哪里是API调用函数代码和测试用例代码。

export async function getUserTest() {
    fetch(config.apiUrl.myFleetAPI, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s'
        }
    })
        .then((response) => {
            return response.json();
        })
        .catch((reject) => console.log(reject));
    
}

测试用例代码。

从“反应”导入反应; 从 '../Service/Dashboard/Dashboard' 导入 { getUserTest };

global.fetch = jest.fn();
const mockAPICall = (option, data) => global.fetch.mockImplementation(() => Promise[option](data));

describe('Car Components component', () => {
    describe('when rendered', () => {
        it('should call a fetchData function', async () => {
            const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };

            mockAPICall('resolve', testData);
            return getUserTest().then((data) => {
                expect(data).toEqual(testData);
            });
        });
    });
});

这是我在尝试运行测试用例时遇到的错误。

 Car Components component
    when rendered
      ✕ should call a fetchData function (5 ms)

  ● Car Components component › when rendered › should call a fetchData function

    expect(received).toEqual(expected) // deep equality

    Expected: {"current_user": "Rahul Raj", "name": "Lafarge"}
    Received: undefined

      65 |             mockAPICall('resolve', testData);
      66 |             return getUserTest().then((data) => {
    > 67 |                 expect(data).toEqual(testData);
         |                              ^
      68 |             });
      69 |         });
      70 |     });

      at src/Test/MainScreen.test.js:67:30

  console.log
    TypeError: response.json is not a function
        at /Users/rahulraj/Documents/Workproject/Vivafront/lafargeClone/src/Service/Dashboard/Dashboard.js:44:29
        at processTicksAndRejections (internal/process/task_queues.js:93:5)

【问题讨论】:

    标签: javascript reactjs unit-testing react-testing


    【解决方案1】:

    你的代码有两个问题:

    1. fetch 函数的解析值是Response,它有一个.json() 方法,你忘了模拟它。

    2. 你忘了像return fetch(/.../)一样返回承诺。这会导致测试用例中的promise链不等待fetch promise完成,这就是为什么返回结果是undefined

    例如

    api.js:

    const config = {
      apiUrl: {
        myFleetAPI: 'http://localhost:3000/api',
      },
    };
    export async function getUserTest() {
      return fetch(config.apiUrl.myFleetAPI, {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s',
        },
      })
        .then((response) => {
          return response.json();
        })
        .catch((reject) => console.log(reject));
    }
    

    api.test.js:

    import { getUserTest } from './api';
    
    describe('68771600', () => {
      test('should pass', () => {
        const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };
    
        const response = { json: jest.fn().mockResolvedValueOnce(testData) };
        global.fetch = jest.fn().mockResolvedValueOnce(response);
    
        return getUserTest().then((data) => {
          expect(data).toEqual(testData);
        });
      });
    });
    

    测试结果:

     PASS  examples/68771600/api.test.js (9.885 s)
      68771600
        ✓ should pass (3 ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |      80 |      100 |   66.67 |      80 |                   
     api.js   |      80 |      100 |   66.67 |      80 | 18                
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        10.794 s
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2019-04-21
      • 2020-03-20
      • 2022-01-06
      • 2022-01-19
      • 2019-05-26
      • 1970-01-01
      • 2014-12-15
      • 2018-02-24
      相关资源
      最近更新 更多