angular - 无法在角度单元测试中模拟服务并返回数据 - 未定义
问题描述
我有以下组件,我正在尝试为其编写单元测试。当我运行以下测试时,我看到了
console.log('**fav**' + favorite[`isFavorite`]);
因为undefined
我认为我试图通过模拟服务返回的数据没有被返回。我的理解是,为了测试它,我应该模拟服务并返回数据,然后调用handleData
并执行。我犯的错误在哪里?
ngOnInit(): void {
this.favoriteService.getData().subscribe(item => {
if (Object.keys(item).length) {
this.handleData(item);
}
});
}
handleData(favorite) {
console.log('**fav**' + favorite[`isFavorite`]);
if (favorite[`isFavorite`]) {
console.log('****1****');
// some logic
} else {
// some logic
}
}
以下是我的规格文件 -
describe('FavoritesComponent', () => {
let component: FavoritesComponent;
let fixture: ComponentFixture<FavoritesComponent>;
let stubFavoriteGatewaySpec: StubFavoriteGatewaySpec;
let spyFavoriteService: jasmine.SpyObj<FavoriteService>;
const favouriteData = [
{
tickerTypeName: 'Market Price',
type: 'MP',
headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
data: [
[1, '1.020'],
[0, '-0.250'],
[-5, '-4.560'],
[-149, '-149.000'],
],
isFavorite: true,
}
];
beforeEach(async(() => {
stubFavoriteGatewaySpec = new StubFavoriteGatewaySpec();
spyFavoriteService = jasmine.createSpyObj('FavoriteService', [
'getData',
]);
spyFavoriteService.getData.and.returnValues(of(favouriteData));
TestBed.configureTestingModule({
imports: [MatExpansionModule],
declarations: [FavoritesComponent],
providers: [
{ provide: FavoritesGateway, useValue: stubFavoriteGatewaySpec },
{ provide: FavoriteService, useValue: spyFavoriteService },
],
})
.compileComponents()
.catch(console.log);
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(FavoritesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
解决方案
//嘲笑
const favouriteData = {
tickerTypeName: 'Market Price',
type: 'MP',
headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
data: [
[1, '1.020'],
[0, '-0.250'],
[-5, '-4.560'],
[-149, '-149.000'],
],
isFavorite: true,
};
//测试
it(
'should set the favorite to true onload',
fakeAsync(() => {
spyOn(spyFavoriteService, 'getData').and.returnValue(of(favouriteData));
component.ngOnInit();
expect(component.isFavorite).toBeTruthy();
//test your other logic
})
);
无需监视beforeEach
,在测试级别模拟它。不确定您要在句柄函数中执行什么操作,如果您有这样的组件变量,isFavorite
那么它应该可以工作。
如果使用 Angular 12 使用waitForAync
而不是fakeAsync
.
推荐阅读
- php - 一般错误:1364 字段 'uuid' 没有默认值
- smtp - 我无法在我的 Laravel 项目中发送到 plesk 磁盘邮件主机
- vim - vim中动态打开最大大小
- excel - 如何在 Excel VBA 中调试用户窗体
- android - 使用公共 url 向公众托管 apk 应用程序
- reactjs - 如何使用反应和材料 ui 一次仅显示一个活动项目
- gitlab - 如何使用 GITLAB 功能标志在 CI yml 文件中按顺序运行同一阶段的作业
- angular - 安装后导入 vega-embed
- github - 无法删除 Github 存储库
- javascript - 如何让我的汉堡菜单 JavaScript 工作?