我们试着用回环做个测试。这个测试涉及到调用google,我们希望用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();
});我们如何测试这种方法?如何测试在环回中涉及构造函数中的注入的端点?拜托,我们需要任何帮助。
发布于 2019-10-15 09:17:02
我认为有两种选择:
"services.OAuth2Service",并使用该上下文创建要测试的控制器。在使用@inject的地方,您提供了一个默认值(可能还有指示依赖项是可选的。),例如:
@inject('services.OAuth2Service', { optional: true })
private oauth2Service: OAuth2Service = mockOAuth2Service,在其他地方,这可能对您有用,但您可能不应该用默认的测试对象来污染默认的生产代码。
https://stackoverflow.com/questions/58355660
复制相似问题