如何使用Sinon对Auth0 Management API Node库的管理客户端端点进行Stub?
解决Sinon Stub Auth0 Management API方法失败的问题
我尝试用三种方式Stub Auth0 Management API的getUsersInRole方法,但均未成功,还遇到了ES模块相关错误:
尝试的方法及问题
方法1:直接Stub类原型
import {ManagementClient} from 'auth0'; import sinon from "sinon"; const component = new Auth0App(); const getUsersInRoleStub = sinon.stub(ManagementClient.prototype, 'getUsersInRole'); getUsersInRoleStub.returns([ { roles: ["rol_EOy9RkqdtAb1Jdde"] } ]);
此方式无效,Stub未生效。
方法2:通过全量导入Stub原型
import * as auth0 from 'auth0'; import sinon from "sinon"; const component = new Auth0App(); const getUsersInRoleStub = sinon.stub(auth0.ManagementClient.prototype, 'getUsersInRole'); getUsersInRoleStub.returns([ { roles: ["rol_EOy9RkqdtAb1Jdde"] } ]);
同样无效,Stub未生效。
方法3:Stub导出的类本身
import * as auth0 from 'auth0'; import sinon from "sinon"; const component = new Auth0App(); const getUsersInRoleStub = sinon.stub(auth0, 'ManagementClient'); getUsersInRoleStub.returns({ getUsersInRole: ()=>{ return [ { roles:["rol_EOy9RkqdtAb1Jdde"] } ] } });
执行后出现错误:
TypeError: ES Modules cannot be stubbed
原因分析
- 前两种方法失效,大概率是因为Auth0的ES模块封装导致类原型无法被外部Stub直接修改;
- 第三种方法报错是因为ES模块的导出是只读的,Sinon无法直接Stub模块导出的类。
可行解决方案
方案1:使用Sinon的createStubInstance创建Stub实例并依赖注入
修改你的Auth0App,使其支持传入ManagementClient实例(依赖注入),然后用Sinon创建Stub实例注入:
import {ManagementClient} from 'auth0'; import sinon from "sinon"; // 创建ManagementClient的Stub实例 const mockManagementClient = sinon.createStubInstance(ManagementClient); // 配置getUsersInRole方法的返回值 mockManagementClient.getUsersInRole.returns([ { roles: ["rol_EOy9RkqdtAb1Jdde"] } ]); // 向Auth0App注入Stub实例 const component = new Auth0App({ managementClient: mockManagementClient });
这种方式是测试中最推荐的方案,通过依赖注入解耦代码,Stub更可靠。
方案2:Stub实例而非原型(如果无法修改Auth0App代码)
如果你的Auth0App内部直接实例化ManagementClient,可以尝试在实例创建后Stub其方法,但需要能获取到该实例:
import {ManagementClient} from 'auth0'; import sinon from "sinon"; // 假设Auth0App内部有一个可访问的managementClient属性 const component = new Auth0App(); sinon.stub(component.managementClient, 'getUsersInRole').returns([ { roles: ["rol_EOy9RkqdtAb1Jdde"] } ]);
这种方式需要你的Auth0App暴露内部的ManagementClient实例,灵活性较差。
内容的提问来源于stack exchange,提问作者Jose Gleeson
相关产品推荐
相关产品推荐

