angular - 如何测试异步函数中设置的变量?
问题描述
我试图在执行异步函数后测试变量的值,但是当我尝试读取它时它是一个空数组(变量应该有一个包含对象的数组),我还放了一些 console.log( ) 在函数内部,它工作正常。
这是我第一次使用 Jasmine 和 Karma,所以任何帮助都可以。
我的组件内的功能
async refresh() {
let requestUserProfile;
let data
// this._fuseSplashScreenService.hide();
// this.showLoading('Cargando documentos...');
//requestUserProfile = this.getUserProfile();
this._restService.getDocumentsLimit(100, 1, undefined).subscribe((documents: any) => {
//Here is just a part of this function
this.moreData = documents.data;
});
}
变量 moreData 是我一直在尝试测试的变量。
测试代码;
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeModule, HttpClientModule, RouterTestingModule, NoopAnimationsModule, MatDialogModule ],
declarations: [ DashboardComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
//This is the one
it('should have info', async () =>{
await component.refresh();
console.log(component.moreData);
//expect(component.moreData).not.toBe(null)
})
});
解决方案
问题不在于异步功能或其他东西。在您的测试脚本中,您需要做的是模拟服务并返回一些值,然后它将自动覆盖该变量。
这是您需要做的:
////////////////// Use Injectable and create a mock-service;
@Injectable()
class MockService extends RestService {
////////////////////// Mock your method here
getDocumentsLimit() {
return of({
data: {
// You know what response comes here, so use that here;
someData: 'someDataValue'
}
}
}
}
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeModule, HttpClientModule, RouterTestingModule, NoopAnimationsModule, MatDialogModule ],
declarations: [ DashboardComponent ],
///////////////// ADD THIS LINE IN THE PROVIDERS /////////////
providers: [
{
provide: RestService,
useClass: MockService
}
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
//This is the one
////////////////////// YOUR TEST CASE WILL BECOME THIS
it('should have info', () =>{
spyOn(component, 'refresh').and.callThrough();
component.refresh();
expect(component.refresh).toHaveBeenCalled();
})
});
推荐阅读
- node.js - 如何防止 Mocha 在测试文件之间保留要求缓存?
- java - Movesense 展示应用程序,我无法更改采样率
- python - 使用 CSV 文件中的列表创建嵌套字典
- php - 传递给 Pheanstalk\Job::__construct() 的参数 2 必须是字符串类型,给定 null
- ios - 通过共享 iCloud 文件夹在 OSX / iOS 版本的应用程序之间共享文件时出现问题
- java - 为什么从类与类加载器加载文件的结果不一致
- elasticsearch - 为什么在 ES 7.6.1 中从 ES 6.4.2 恢复快照后,我的索引文档不能按 id 获取?
- c++ - Gracefully shutdown boost::beast HTTPServer
- php - 使用 Laravel PHP 读取 PDF 文件错误:readfile($path): failed to open stream: No such file or directory
- react-native - 在平面列表中从 API 呈现 GET JSON 响应时出现问题