使用Jest+TypeScript编写Express接口测试失败,求解决及测试用例指导
解决Jest+TypeScript测试Express接口的报错及正确编写GET测试用例
报错原因分析
报错TypeError: (0 , express_1.default) is not a function主要源于两个问题:
- Express API文件未导出
app实例,测试文件无法正确导入使用。 - TypeScript编译或Jest配置未处理好ES模块与CommonJS模块的兼容性,导致Express的导入逻辑在编译后出现异常。
解决步骤
1. 修正Express API文件的导出
在index.ts末尾添加app实例的导出,让测试文件能正常导入:
// index.ts 末尾新增 export default app;
2. 配置TypeScript与Jest
先安装必要的开发依赖:
npm install --save-dev jest ts-jest @types/jest @types/express @types/supertest
创建或修改tsconfig.json,确保编译后的模块格式兼容CommonJS:
{ "compilerOptions": { "target": "ES6", "module": "CommonJS", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules", "__test__"] }
创建jest.config.js配置Jest使用ts-jest预设处理TypeScript:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', testMatch: ['**/__test__/**/*.ts'], moduleFileExtensions: ['ts', 'js'] };
3. 修正测试文件的错误
测试文件存在拼写错误resopose,同时确保导入路径与API文件位置匹配:
// __test__/index.test.ts import request from 'supertest'; import app from "../src/index"; // 若API文件在src目录下,调整路径匹配实际结构 describe("GET /getaccsummary", () => { it("should return account summary with status 200", async () => { const response = await request(app).get('/getaccsummary'); expect(response.status).toBe(200); }); });
完善GET请求测试用例
除了基础的状态码断言,还应覆盖不同场景,保证测试完整性:
测试账户列表接口
describe("GET /getaccsummary", () => { it("returns 200 and correct account list", async () => { const response = await request(app).get('/getaccsummary'); expect(response.status).toBe(200); expect(response.body).toBeInstanceOf(Array); expect(response.body.length).toBe(3); expect(response.body[0]).toHaveProperty("id", 1); expect(response.body[0].name).toBe("Atharva"); }); });
测试单个账户查询接口
describe("GET /account/:id", () => { it("returns 200 and valid account data for existing ID", async () => { const response = await request(app).get("/account/2"); expect(response.status).toBe(200); expect(response.body.name).toBe("Soham"); expect(response.body.accType).toBe("Current"); }); it("returns 500 error for non-existent account ID", async () => { const response = await request(app).get("/account/999"); expect(response.status).toBe(500); expect(response.text).toBe("Account not Found"); }); });
运行测试
执行以下命令启动测试:
npm test
内容的提问来源于stack exchange,提问作者Aimless
相关产品推荐
相关产品推荐

