[英]How to test unit test a void function in Angular?
我是 angular 的新手,我正在測試我的 Login 組件,它是這樣的。它有一個handleLogin()
函數,它是無效的。它重定向到另一個函數,如下所示。
如何測試此功能? 它重定向到一些其他函數,該函數也重定向到其他地方。 如何測試這么復雜的功能。
由於涉及一個服務並且您應該“UNIT”測試該組件,所以您應該模擬該服務並期望在您調用組件上的handleLogin
方法時調用它的方法。
像這樣的東西:
import { LoginComponent } from './login.component';
import { LoginService } from '../../services/login.service';
import { AuthenticationService } from './auth.service';
describe('Component: Login', () => {
let component: LoginComponent;
let service: LoginService;
let spy: any;
beforeEach(() => {
service = new LoginService();
component = new LoginComponent(service);
});
afterEach(() => {
service = null;
component = null;
});
describe('Method: handleLogin', () => {
it('should call the `redirectToAuth` method on the `LoginService`', () => {
spy = spyOn(service, 'redirectToAuth');
component.handleLogin();
expect(spy).toHaveBeenCalled();
});
});
});
it('should not be called redirect after login function', () => {
const loginService = TestBed.inject(LoginService);
const authService = TestBed.inject(AuthenticationService);
spyOn(authService, 'isLoggedIn').and.returnValue(false); // FALSE
component.ngOnInit();
expect(loginSerive.redirectAfterLogin).not.toHaveBeenCalled();
}
it('should be called redirect after login function', () => {
const loginService = TestBed.inject(LoginService);
const authService = TestBed.inject(AuthenticationService);
spyOn(authService, 'isLoggedIn').and.returnValue(true);
component.ngOnInit();
expect(loginSerive.redirectAfterLogin).toHaveBeenCalled();
}
it('should be called redirectToAuth function', () => {
const loginService = TestBed.inject(LoginService);
spyOn(loginService, 'redirectToAuth').and.callFake;
component. handleLogin();
expect(loginSerive.redirectToAuth).toHaveBeenCalled();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.