unit-testing - 如何在 Loopback 4 的验收测试中模拟服务
问题描述
我正在 Loopback 4 中编写一些测试,我需要模拟/存根服务,我的意思是我需要用存根替换绑定中的它。但我找不到如何做到这一点。
我想写这样的测试:
it(`should work if a user was found for the token in 'authorization' header`, async () => {
await client
.get('/mock')
.set('Authorization', 'Bearer a-good-token')
.expect(200);
});
为此,我必须在before
方法中的每个测试套件之前启动一个应用程序。我启动我的应用程序,然后尝试更改我的服务的绑定:
before('setupApplication', async () => {
app = new MyApplication();
await app.boot();
app.bind('services.WebAuthService').to(MockWebAuthService); // to replace with the mocked one
app.controller(MockController);
await app.start();
}
我尝试了不同的方法来编写我的 MockWebAuthService :
- 使用 Sinon 存根:
const utilisateur = sinon.createStubInstance(Utilisateur);
utilisateur.uId = 123456;
const verifyCredentialsStub = sinon.stub().resolves(undefined);
verifyCredentialsStub
.withArgs({token: 'a-good-token'})
.resolves(utilisateur);
const MockWebAuthService: WebAuthService = sinon.createStubInstance(
WebAuthService,
{
verifyCredentials: verifyCredentialsStub,
convertToUserProfile: sinon.stub(),
},
);
- 或使用新课程:
class MockWebAuthService implements UserService<Utilisateur, Credentials> {
async verifyCredentials(credentials: Credentials): Promise<Utilisateur> {
const utilisateur = sinon.createStubInstance(Utilisateur);
utilisateur.uId = 123456;
if (credentials.token === 'a-good-token') {
return utilisateur;
} else {
throw new Error('invalid token');
}
}
convertToUserProfile(utilisateur: Utilisateur): UserProfile {
return {} as UserProfile;
}
}
但这些都不起作用。在我的WebAuthService
组件中注入的仍然是 from src/services
,而不是嘲笑的。
知道我应该怎么做吗?
在此先感谢您的帮助 !
解决方案
我发现了我的问题。我绑定存根服务的方式是错误的。
它是这样工作的:
app.getBinding('services.WebAuthService').to(MockWebAuthService);
推荐阅读
- javascript - 如何将事件注册到 Youtube 视频播放进度?
- netbeans - 我的来自 netbeans 的 layer.xml 有什么问题?
- bash - 在 Windows 10 中将 Git BASH 用于非 git 任务是否可以接受?
- solidity - 数组返回“未声明的标识符。您的意思是“候选人”还是“候选人”?
- c# - 语音转文本示例上的 Unity Watson SDK 错误
- sql - SQL - 从另一个表更新表 - 语法错误
- angular - 链接 Angular Firestore 集合
- javascript - 从 JavaScript 函数写入 HTML 元素
- scikit-learn - “AdaboostRegression”在机器学习领域的算法细节是什么?
- android - 从目录获取文档/集合列表的问题