如何在Mocha.js+Chai中实现API授权以测试SAP维护通知API
SAP维护通知API Mocha测试授权方案
问题根源分析
你遇到的两个核心问题:
- 错误的令牌获取路径:SAP维护通知API不使用
/auth/sign_in,而是遵循OAuth2 Client Credentials流获取令牌 - 缺失API Key:SAP API Hub所有请求必须携带
APIKey请求头,错误FailedToResolveAPIKey就是因为这个头没传
正确实现步骤
1. 收集必要凭证
从SAP相关平台获取以下信息:
- API Key:在SAP API Hub的目标API详情页,进入「API Key」标签生成并复制
- OAuth凭证:从SAP BTP Cockpit获取
CLIENT_ID、CLIENT_SECRET,以及对应租户的令牌端点URL(例如https://your-tenant.authentication.sap.hana.ondemand.com/oauth/token) - API基础URL:SAP维护通知API的沙箱地址为
https://sandbox.api.sap.com/op_api_maintnotification
2. Mocha+Chai测试代码实现
const chai = require('chai'); const chaiHttp = require('chai-http'); const expect = chai.expect; chai.use(chaiHttp); // 全局存储令牌和配置 let bearerToken; const API_KEY = '替换为你的SAP API Key'; const OAUTH_SETTINGS = { tokenUrl: '替换为你的OAuth令牌端点', clientId: '替换为你的Client ID', clientSecret: '替换为你的Client Secret' }; const API_BASE_URL = 'https://sandbox.api.sap.com/op_api_maintnotification'; // 测试前统一获取令牌 before(async () => { const tokenRes = await chai.request(OAUTH_SETTINGS.tokenUrl) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ grant_type: 'client_credentials', client_id: OAUTH_SETTINGS.clientId, client_secret: OAUTH_SETTINGS.clientSecret }); expect(tokenRes.status).to.eq(200); bearerToken = tokenRes.body.access_token; if (!bearerToken) throw new Error('令牌获取失败,返回的access_token为空'); }); describe('SAP维护通知API CRUD测试', () => { it('GET:获取维护通知列表', async () => { const res = await chai.request(API_BASE_URL) .get('/A_MaintenanceNotification') .set('APIKey', API_KEY) .set('Authorization', `Bearer ${bearerToken}`) .set('Accept', 'application/json'); expect(res.status).to.eq(200); expect(res.body).to.be.an('object'); }); // POST/PUT/DELETE测试用例同理,必须携带APIKey和Authorization头 it('POST:创建维护通知', async () => { const newNotification = { // 按API文档填充请求体字段 MaintenanceNotificationType: 'M2', Description: '测试通知' }; const res = await chai.request(API_BASE_URL) .post('/A_MaintenanceNotification') .set('APIKey', API_KEY) .set('Authorization', `Bearer ${bearerToken}`) .set('Content-Type', 'application/json') .send(newNotification); expect(res.status).to.eq(201); expect(res.body.MaintenanceNotification).to.not.be.empty; }); });
3. 常见问题排查
- 令牌为空:检查OAuth凭证是否正确,确保Client ID/Secret和令牌端点属于同一个SAP租户
- API Key错误:确认API Key是从目标API的「API Key」标签生成,而非其他API
- 路径无效:严格遵循SAP API文档里的路径,比如创建通知是
POST /A_MaintenanceNotification,不是自定义路径 - 权限不足:在SAP BTP Cockpit中,确保你的OAuth客户端已分配维护通知API的相关角色
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

