我们正在尝试使用环回进行测试。测试涉及调用google API,我们想用Sinon模拟它。
控制器:
[...]
在构造函数中:
@inject('services.OAuth2Service')
private oauth2Service: OAuth2Service
[...]
在端点中:
@post('/user-accounts/authenticate/oauth2', {
async authenticateOauth2(
@requestBody() oauthRequest: OAuthId,
@inject(RestBindings.Http.REQUEST) _req: Request,
): Promise<AccessToken> {
const email = await this.oauth2Service.getOAuth2User(oauthRequest); // The method to mock.
....
}
考试:
it('oauth2 authentication with google', async () => {
//Create a spy for the getOAuth2User function
inject.getter('services.OAuth2Service');
var oauth2Service: OAuth2Service;
var setOauthSpy = sinon.spy(oauth2Service, "getOAuth2User"); // Error: Variable 'oauth2Service' is used before being assigned
const res = await client
.post('/user-accounts/authenticate/oauth2')
.set('urlTenant', TEST_TENANT_URL1A)
.set('userType', TEST_USERTYPE1)
.send({
code: TEST_GOOGLE_AUTH2_CODE_KO,
providerId: TEST_GOOGLE_PROVIDER,
redirectUri: TEST_GOOGLE_REDIRECT_URI,
})
.expect(401);
expect(res.body.error.message).to.equal('The credentials are not correct.');
setOauthSpy.restore();
});
我们如何测试这种方法?我们如何测试一个在环回构造函数中涉及注入的端点?拜托,我们需要任何帮助。