如何为JavaScript REST GET请求编写测试用例?求代码修正
针对封装REST GET请求的测试用例编写方案
原测试代码的问题分析
原测试仅通过jest.spyOn监听了方法调用,但未实际触发get方法执行,也没有模拟https.get的行为来测试核心的响应处理、回调触发逻辑,完全没有覆盖到handleResponse和checkJSONResponse的分支逻辑,无法验证代码的正确性。
正确的测试用例实现
以下是使用Jest编写的、覆盖所有核心场景的测试代码:
首先需要在测试文件顶部mock https模块:
const https = require('https'); const crud = require('./path-to-your-crud-module'); // 替换为你的模块路径 jest.mock('https');
1. 测试GET请求成功且返回JSON响应
describe('CRUD GET method tests', () => { it('should call callback with parsed JSON when request succeeds', (done) => { // 模拟响应对象 const mockResponse = { statusCode: 200, on: jest.fn((event, handler) => { if (event === 'data') { handler(JSON.stringify({ id: 1, name: 'test' })); } else if (event === 'end') { handler(); } return mockResponse; }) }; // 模拟https.get的行为 https.get.mockImplementation((options, callback) => { callback(mockResponse); return { on: jest.fn() }; }); // 定义测试用的回调函数 const mockCallback = jest.fn((data) => { expect(data).toEqual({ id: 1, name: 'test' }); expect(mockCallback).toHaveBeenCalledTimes(1); done(); // 标记异步测试完成 }); // 调用被测试的get方法 crud.get({}, '/test', mockCallback, jest.fn()); // 验证https.get被正确调用 expect(https.get).toHaveBeenCalled(); });
2. 测试GET请求返回非2xx状态码,触发errorCallback
it('should call errorCallback when response status is non-2xx', (done) => { const mockResponse = { statusCode: 404, on: jest.fn((event, handler) => { if (event === 'data') { handler('Not Found'); } else if (event === 'end') { handler(); } return mockResponse; }) }; https.get.mockImplementation((options, callback) => { callback(mockResponse); return { on: jest.fn() }; }); const mockErrorCallback = jest.fn((data) => { expect(data).toBe('Not Found'); expect(mockErrorCallback).toHaveBeenCalledTimes(1); done(); }); crud.get({}, '/invalid', jest.fn(), mockErrorCallback); });
3. 测试请求发生网络错误,触发errorCallback
it('should call errorCallback when request fails', (done) => { const mockError = new Error('Network Error'); https.get.mockImplementation(() => { const mockRequest = { on: jest.fn((event, handler) => { if (event === 'error') { handler(mockError); } return mockRequest; }) }; return mockRequest; }); const mockErrorCallback = jest.fn((error) => { expect(error).toBe(mockError); expect(mockErrorCallback).toHaveBeenCalledTimes(1); done(); }); crud.get({}, '/error', jest.fn(), mockErrorCallback); });
4. 测试返回非JSON格式的响应,checkJSONResponse处理为空对象
it('should return empty object when response is not valid JSON', (done) => { const mockResponse = { statusCode: 200, on: jest.fn((event, handler) => { if (event === 'data') { handler('<html>Invalid JSON</html>'); } else if (event === 'end') { handler(); } return mockResponse; }) }; https.get.mockImplementation((options, callback) => { callback(mockResponse); return { on: jest.fn() }; }); const mockCallback = jest.fn((data) => { expect(data).toEqual({}); expect(mockCallback).toHaveBeenCalledTimes(1); done(); }); crud.get({}, '/non-json', mockCallback, jest.fn()); }); });
测试用例编写学习资源推荐
- Jest官方异步测试指南:重点掌握模块mock、异步回调测试、事件模拟的方法,理解如何隔离外部依赖
- 前端单元测试核心思路:学习如何拆分测试场景,覆盖代码的所有分支逻辑(如状态码判断、异常处理)
- API封装测试最佳实践:积累异步API测试的经验,包括模拟不同响应、验证回调触发时机与参数正确性
内容的提问来源于stack exchange,提问作者TAK
相关产品推荐
相关产品推荐

