我剛開始學習 Jasmine,所以當需要檢查重定向是否傳遞到正確的頁面時,我面臨著任務。我非常感謝任何幫助。鏈接到主題或只是代碼示例。我想在點擊鏈接和第二種情況后檢查重定向 - 成功授權后。在下面的示例中,我嘗試實作第一種情況。例如我有一個登錄組件:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../auth.service';
import {
AbstractControl,
FormBuilder,
FormGroup,
Validators,
} from '@angular/forms';
import { PushNotificationService } from 'src/app/push-notification.service';
@Component({
selector: 'app-autorization',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
isPasswordHidden = true;
form!: FormGroup;
public passwordInput!: AbstractControl;
constructor(
private authService: AuthService,
private fb: FormBuilder,
private pushNotificationService: PushNotificationService
) {}
ngOnInit(): void {
this.form = this.fb.group({
username: ['', [Validators.required, Validators.minLength(3)]],
password: ['', [Validators.required, Validators.minLength(6)]],
});
this.passwordInput = this.form.controls['password'];
}
userLoginClick() {
if (!this.form.valid) {
this.pushNotificationService.createNotification(
'Data format is incorrect'
);
return false;
}
const user = {
username: this.form.controls['username'].value,
password: this.form.controls['password'].value,
};
this.authService.authUser(user);
}
togglePassVisibility(e: Event) {
e.preventDefault();
this.isPasswordHidden = !this.isPasswordHidden;
}
}
來自 authService 的函式:
authUser(user: User) {
return this.http
.post(
`${environment.domain}${BackendRoutes.Login}`,
user,
this.httpOptions
)
.subscribe((data: any) => {
if (!data.success) {
this.pushNotificationService.createNotification(data.message);
} else {
this.router.navigate([`/${Paths.Lobby}`]);
this.storeUser(data.token, data.user);
}
});
}
我試圖做這樣的事情:
describe('Router redirects to proper pages', () => {
let location: Location;
let router: Router;
let fixture: any;
let redirectLink!: any;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes(routes),
HttpClientTestingModule,
],
declarations: [LobbyComponent, SignupComponent],
providers: [FormBuilder, MatSnackBar, Overlay],
});
router = TestBed.inject(Router);
location = TestBed.inject(Location);
fixture = TestBed.createComponent(LoginComponent);
router.initialNavigation();
const compiled = fixture.debugElement;
redirectLink = compiled.query(
By.css('[routerLink="/signup"]')
).nativeElement;
});
it('text', fakeAsync(() => {
redirectLink.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(router.url).toEqual('/signup');
}));
});
實際上我沒有得到預期的結果=)任何幫助都是有價值的!
uj5u.com熱心網友回復:
建議您一次只測驗一個類,任何依賴項都偽造值,然后驗證您的類與該依賴項之間的互動。
在這種情況下,您已經撰寫了一個要驗證其正常作業的 LoginComponent。
首先,讓我們討論一下TestBed。我們需要匯入我們的組件需要的任何提供程式和模塊,但我們會偽造我們撰寫的任何內容。
由于您的代碼登錄,我將為此撰寫一個基本測驗。
let authService: jasmine.spyObj<AuthService>;
beforeEach(() => {
// create a fake that has the same methods we will want to verify
const fakeAuthService = jasmine.createSpyObj<AuthService>('auth', ['authUser']);
TestBed.configureTestingModule({
imports: [
// the auth service needs these, but we don't here
// RouterTestingModule.withRoutes(routes),
// HttpClientTestingModule,
],
// not necessary unless the html contains them
// declarations: [LobbyComponent, SignupComponent],
declarations: [LoginComponent],
providers: [FormBuilder, MatSnackBar, Overlay,
{ provide: AuthService, useValue: fakeAuthService}
],
});
authService = TestBed.inject<AuthService> as jasmine.spyObj<AuthService>;
fixture = TestBed.createComponent(LoginComponent);
});
it('should log in', () => {
// interact with the html, as that is the public interface of your component
setTextInput('#userName', 'someUser');
setTextInput('#password', 'somePassword');
click('#loginButton');
// verify the interaction with the dependency
// we don't care (from this spec) what the auth service did
// if this function returned a result we would want to verify that we did the correct thing with it
expect(authService.authUser).toHaveBeenCalledWith({ username: 'someUser', password: 'somePassword' })
});
function setTextInput(selector: string, value: string): void {
const input = fixture.debugElement.query(By.css(selector));
input.nativeElement.value = value;
input.nativeElement.dispatchEvent(new Event('input'));
}
click(selector: string): void {
const clicker = fixture.debugElement.query(By.css(selector));
clicker.triggerEventHandler('click', null);
fixture.detectChanges();
}
我發現最接近我使用的風格的是testing-angular 免費電子書
當您測驗您的身份驗證服務時,您將測驗路由是否有效。在這種情況下,我通常會為路由器提供一個假物件,因為我只想檢查路由器是否按照我的預期呼叫。
mockRouter = jasmine.createSpyObj('router', ['navigate']);
...
{ provide: Router, useValue: mockRouter },
要測驗您的組件是否更改路由,您可以執行類似的操作。你有什么測驗路由器做了它應該做的事情。您想要的是確保您與路由器的互動方式符合您的期望。
it('text', () => {
redirectLink.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['/signup']);
});
希望這能讓你開始。隨時發布其他問題并標記我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/528204.html
