首页 > 解决方案 > 如何在 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 :

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,而不是嘲笑的。

知道我应该怎么做吗?

在此先感谢您的帮助 !

标签: unit-testingsinonloopback4

解决方案


我发现了我的问题。我绑定存根服务的方式是错误的。

它是这样工作的:

app.getBinding('services.WebAuthService').to(MockWebAuthService);

推荐阅读