Angular 9单元测试一定要怎么写?
How Angular 9 unit test must be written?
我是 Angular 的新手,我很难理解如何为一段代码编写单元测试。有人可以向我解释如何为以下代码编写单元测试吗?
toggleClassActive(station: any): void {
this.isDisabled = false;
this.stationsList.map((st) => {
if (st.id === station.id) {
st.active = true;
} else {
st.active = false;
}
});
}
给出这个示例组件
export class FooComponent {
isDisabled = true;
stationsList: Array<{ id: number, active: boolean }> = [
{id: 1, active: false}, {id: 2, active: true},
];
constructor() {
}
toggleClassActive(station: { id: number, active: boolean }): void {
this.isDisabled = false;
this.stationsList.map((st) => {
if (st.id === station.id) {
st.active = true;
} else {
st.active = false;
}
});
}
}
这是该方法的单元测试
import {TestBed} from '@angular/core/testing';
import {FooComponent} from './foo.component';
describe('FooComponent', () => {
let component: FooComponent;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
FooComponent,
],
});
component = TestBed.inject(FooComponent);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should toggle active class', () => {
// Optionally test the initial values // state
expect(component.stationsList).toEqual([
{id: 1, active: false}, {id: 2, active: true},
]);
expect(component.isDisabled).toEqual(true);
// Trigger the effect
component.toggleClassActive({id: 1, active: false});
// Assert the expected changes
expect(component.stationsList).toEqual([
{id: 1, active: true}, {id: 2, active: false},
]);
expect(component.isDisabled).toEqual(false);
});
});
我是 Angular 的新手,我很难理解如何为一段代码编写单元测试。有人可以向我解释如何为以下代码编写单元测试吗?
toggleClassActive(station: any): void {
this.isDisabled = false;
this.stationsList.map((st) => {
if (st.id === station.id) {
st.active = true;
} else {
st.active = false;
}
});
}
给出这个示例组件
export class FooComponent {
isDisabled = true;
stationsList: Array<{ id: number, active: boolean }> = [
{id: 1, active: false}, {id: 2, active: true},
];
constructor() {
}
toggleClassActive(station: { id: number, active: boolean }): void {
this.isDisabled = false;
this.stationsList.map((st) => {
if (st.id === station.id) {
st.active = true;
} else {
st.active = false;
}
});
}
}
这是该方法的单元测试
import {TestBed} from '@angular/core/testing';
import {FooComponent} from './foo.component';
describe('FooComponent', () => {
let component: FooComponent;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
FooComponent,
],
});
component = TestBed.inject(FooComponent);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should toggle active class', () => {
// Optionally test the initial values // state
expect(component.stationsList).toEqual([
{id: 1, active: false}, {id: 2, active: true},
]);
expect(component.isDisabled).toEqual(true);
// Trigger the effect
component.toggleClassActive({id: 1, active: false});
// Assert the expected changes
expect(component.stationsList).toEqual([
{id: 1, active: true}, {id: 2, active: false},
]);
expect(component.isDisabled).toEqual(false);
});
});