我的组件上有这个新的角度信号变量:
private employees: Signal<Employee[]> = this.employeesService.filteredEmployeesSignal;
public employeesDataSource = computed(
() => new MatTableDataSource<Employee>(this.employees())
);
一切正常,直到测试因以下错误而失败:
this.employees is not a function
当尝试访问 this.employees()
信号值时。它检测为函数而不是信号值获取器。
我尝试获取计算信号内其他局部常量的值,但错误仍然存在。
我们可以模拟服务并在模拟服务上配置
signal
,然后检查返回值!
规格ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';
import { signal } from '@angular/core';
import { EmployeesService } from './employees.service';
describe('App tests', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let employeeServiceMock!: EmployeesService;
beforeEach(async () => {
employeeServiceMock = {
filteredEmployeesSignal: signal([]),
};
await TestBed.configureTestingModule({
imports: [CommonModule],
providers: [
{
provide: EmployeesService,
useValue: employeeServiceMock,
},
],
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should set employees property', () => {
expect(component['employees']()).toEqual([]);
});
});
cd test
-> npm i
-> npm run test