如何用Jest在TypeScript中模拟@azure/functions的HttpRequest与InvocationContext
如何在TypeScript中模拟Azure Functions的HttpRequest和InvocationContext进行测试
1. 准备测试依赖
以Jest为例,先安装必要的测试工具:
npm install --save-dev jest ts-jest @types/jest
然后在项目根目录创建jest.config.js,配置TypeScript支持:
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: 'ts-jest', testEnvironment: 'node', };
2. 手动模拟InvocationContext和HttpRequest
由于InvocationContext和HttpRequest都是TypeScript接口,你只需要模拟函数实际用到的属性/方法即可,无需实现完整接口:
模拟InvocationContext
你的函数用到了context.log和context.invocationId,对应模拟如下:
const mockContext: Partial<InvocationContext> = { log: jest.fn(), // 用Jest mock函数记录调用行为 invocationId: 'test-invocation-123' };
使用Partial<>可以避免必须实现接口的所有属性,TypeScript会兼容这种部分实现。
模拟HttpRequest
你的函数用到了request.url,基础模拟如下:
const mockRequest: Partial<HttpRequest> = { url: 'http://localhost:7071/api/create' };
如果后续函数用到request.body、request.method或request.json()这类方法,直接补充模拟即可:
// 示例:模拟请求体解析方法 const mockRequest: Partial<HttpRequest> = { url: 'http://localhost:7071/api/create', json: jest.fn().mockResolvedValue({ productName: 'Test Product' }) };
3. 编写测试用例
创建测试文件(比如create.test.ts),导入目标函数后编写测试逻辑:
import { create } from './your-function-file-path'; import { HttpRequest, InvocationContext } from "@azure/functions"; describe('create function', () => { it('should return 200 status with product data', async () => { // 模拟cosmosdb返回的product数据(根据实际业务调整) const mockProduct = { id: '1', name: 'Sample Product' }; // 提示:如果product是通过第三方依赖获取的,需提前mock该依赖的返回值 // 创建模拟对象 const mockContext: Partial<InvocationContext> = { log: jest.fn(), invocationId: 'test-id' }; const mockRequest: Partial<HttpRequest> = { url: 'http://test-url/api/create' }; // 调用函数,用类型断言转换为完整接口类型 const result = await create(mockRequest as HttpRequest, mockContext as InvocationContext); // 断言返回结果 expect(result.status).toBe(200); expect(result.jsonBody?.product).toEqual(mockProduct); // 断言日志方法是否被正确调用 expect(mockContext.log).toHaveBeenCalledWith( `addFeedback processing request for url "${mockRequest.url}, ${mockContext.invocationId}"` ); }); });
补充说明
- 如果需要更全面的模块模拟,可以使用
jest.mock('@azure/functions')来mock整个Azure Functions模块,但手动模拟所需属性通常更简洁高效。 - 所有mock函数都可以通过Jest的断言方法验证调用次数、参数是否符合预期。
内容的提问来源于stack exchange,提问作者ahmedsalihh
相关产品推荐
相关产品推荐

