如何在Angular中模拟AWS Amplify库? [英] How to mock AWS Amplify library in Angular?
问题描述
当我使用Karma运行套件测试时,我似乎收到了一个错误,该错误似乎来自AWS Amplify.
I am getting an error that seems to come from AWS Amplify when I run the suite of tests with Karma.
AuthEffects
login
√ should not dispatch any action
√ should call setItem on LocalStorageService
Chrome 78.0.3904 (Windows 10.0.0) ERROR
An error was thrown in afterAll
Uncaught TypeError: Cannot read property 'clientMetadata' of undefined thrown
据此,我认为此错误是从上次启动的测试:AuthEffects
From that I suppose that this error is thrown from the last test that was launched: AuthEffects
在AuthEffects中,我必须这样做才能使AWS放大工作正常
In my AuthEffects, I had to do that to make AWS amplify working
import { Auth } from 'aws-amplify';
//...
const promise = Auth.signIn(username, password);
我不知道如何模拟对Cognito的API访问.通常,我通过依赖注入为构造函数提供Mock服务,以避免与API的真正连接.在这里,它直接导入到组件中.
I don't understand how I can mock this API access to the Cognito. Usually, I provide a Mock service to the constructor by dependendies injection to avoid real connection to the API. Here it's directly imported in the component.
规范文件:
describe('login', () => {
it('should not dispatch any action', () => {
const actions = new Actions(EMPTY);
const effect = new AuthEffects(
//...
);
const metadata = getEffectsMetadata(effect);
expect(metadata.login).toEqual({ dispatch: false });
});
it('should call setItem on LocalStorageService', () => {
const loginAction = new ActionAuthLogin('test', 'Test1234!');
const source = cold('a', { a: loginAction });
const actions = new Actions(source);
const effect = new AuthEffects(
//...
);
effect.login.subscribe(() => {
expect(localStorageService.setItem).toHaveBeenCalledWith(AUTH_KEY, {
isAuthenticated: true
});
});
});
afterAll(() => {
TestBed.resetTestingModule();
});
});
是否有一种方法可以覆盖从规范文件中导入的内容?
Is there a way to override this import from the spec file ?
推荐答案
我设法摆脱了错误.
您需要在测试文件和以下解决方案中所需的类型中导入Auth.
You need to import Auth in the test file and the types that will be needed in the following solution.
import { Auth } from 'aws-amplify';
import { ClientMetaData, SignInOpts } from '@aws-amplify/auth/src/types/Auth';
现在,重新定义Auth的signIn方法将解决此问题:
Now, redefining the signIn method of the Auth will solve the problem:
describe('AuthEffects', () => {
//...
Auth.signIn = (
usernameOrSignInOpts: string | SignInOpts,
pw?: string,
clientMetadata: ClientMetaData = this._config.clientMetadata
) => of({}).toPromise();
//...
您需要遵循方法的签名才能覆盖它.
You need to follow the signature of the method to override it.
public signIn(
usernameOrSignInOpts: string | SignInOpts,
pw?: string,
clientMetadata: ClientMetaData = this._config.clientMetadata
): Promise<CognitoUser | any>
我不知道它是否是执行它的最佳(更干净)解决方案,但我设法摆脱了错误并控制了Auth实例的行为.
I don't know if it's the best (cleaner) solution to perform it, but I manage to get rid of the error and control the behavior of the Auth instance.
这篇关于如何在Angular中模拟AWS Amplify库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!