扩展JHipster测试-Promise问题

时间:2018-11-20 08:38:49

标签: javascript typescript unit-testing promise jhipster

我正在尝试扩展JHipster的Angular规格测试,并且遇到了问题。

我的目标是模仿“登录”组件中的失败登录。但是我无法从login.service.ts收到伪造的身份验证错误。我已经在mock-login.service.ts中创建了一个方法,但是测试无法通过。
控制台输出:Uncaught (in promise): Object: {}

这是我的测试: login.component.spec.ts Code on GitHub (without my test)

it('should fail authenticate upon login with wrong credentials', inject(
    [],
    fakeAsync(() => {
        // GIVEN
        const credentials = {
            username: 'NonExistingUser',
            password: 'WrongPassword',
            rememberMe: true
        };

        comp.username = 'NonExistingUser';
        comp.password = 'WrongPassword';
        comp.rememberMe = true;
        comp.credentials = credentials;
        mockLoginService.returnAuthenticationError({}); // Here i try to imitate error

        comp.credentials = credentials;

        // WHEN
        comp.login();
        tick(); // simulate async

        // THEN
        expect(comp.authenticationError).toEqual(true);
        expect(mockLoginService.loginSpy).toHaveBeenCalledWith(credentials);
        expect(mockRouter.navigateSpy).not.toHaveBeenCalled();
    })
));

login.component.ts GitHub

login() {
    this.loginService
        .login({
            username: this.username,
            password: this.password,
            rememberMe: this.rememberMe
        })
        .then(() => {
            this.authenticationError = false;
            this.activeModal.dismiss('login success');
            if (this.router.url === '/register' || /^\/activate\//.test(this.router.url) || /^\/reset\//.test(this.router.url)) {
                this.router.navigate(['']);
            }

            this.eventManager.broadcast({
                name: 'authenticationSuccess',
                content: 'Sending Authentication Success'
            });

            // previousState was set in the authExpiredInterceptor before being redirected to login modal.
            // since login is succesful, go to stored previousState and clear previousState
            const redirect = this.stateStorageService.getUrl();
            if (redirect) {
                this.stateStorageService.storeUrl(null);
                this.router.navigate([redirect]);
            }
        })
        .catch(() => {
            this.authenticationError = true;
        });
}

mock-login.service.ts GitHub (without my custom method)

export class MockLoginService extends SpyObject {
    loginSpy: Spy;
    logoutSpy: Spy;
    registerSpy: Spy;
    requestResetPasswordSpy: Spy;
    cancelSpy: Spy;

    constructor() {
        super(LoginService);

        this.setLoginSpy({});
        this.returnAuthenticationError({}); 
        this.logoutSpy = this.spy('logout').andReturn(this);
        this.registerSpy = this.spy('register').andReturn(this);
        this.requestResetPasswordSpy = this.spy('requestResetPassword').andReturn(this);
        this.cancelSpy = this.spy('cancel').andReturn(this);
    }

    setLoginSpy(json: any) {
        this.loginSpy = this.spy('login').andReturn(Promise.resolve(json));
    }

    setResponse(json: any): void {
        this.setLoginSpy(json);
    }

    returnAuthenticationError(json:any): void {
        this.loginSpy = this.spy('login').andReturn(Promise.reject(json));
    }
}

login.service.ts GitHub

export class LoginService {
    constructor(
        private languageService: JhiLanguageService,
        private principal: Principal,
        private authServerProvider: AuthServerProvider
    ) {}

    login(credentials, callback?) {
        const cb = callback || function() {};

        return new Promise((resolve, reject) => {
            this.authServerProvider.login(credentials).subscribe(
                data => {
                    this.principal.identity(true).then(account => {
                        // After the login the language will be changed to
                        // the language selected by the user during his registration
                        if (account !== null) {
                            this.languageService.changeLanguage(account.langKey);
                        }
                        resolve(data);
                    });
                    return cb();
                },
                err => {
                    this.logout();
                    reject(err);
                    return cb(err);
                }
            );
        });
    }

    logout() {
        this.authServerProvider.logout().subscribe();
        this.principal.authenticate(null);
    }
}

我想问题在于我的小知识和理解嘲笑和诺言。

0 个答案:

没有答案