gpt4 book ai didi

javascript - Jasmine 函数 Spy 不适用于 Angular

转载 作者:行者123 更新时间:2023-12-03 04:40:15 25 4
gpt4 key购买 nike

我有一个带有以下测试套件的 angular-cli 项目:

let fakeCellService = {
getCellOEE: function (value): Observable<Array<IOee>> {
return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
}
};

describe('Oee24Component', () => {
let component: any;
let fixture: ComponentFixture<Oee24Component>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Oee24Component],
providers: [{ provide: CellService, useValue: fakeCellService }]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(Oee24Component);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(fakeCellService, 'getCellOEE');
});

it('should get cell oee on init', () => {
component.ngOnInit();
expect(fakeCellService.getCellOEE).toHaveBeenCalled();
});
});

但是,测试中的 Spy 失败了。我知道该函数被调用,因为我在调试器中对此进行了测试。我看不出这与记录的示例有何不同,但想必确实如此!有什么想法吗?

这是我的组件:

@Component({
selector: 'app-oee',
templateUrl: './oee.component.html',
styleUrls: ['./oee.component.css']
})
export class Oee24Component implements OnInit {

constructor(public dataService: CellService) { }

ngOnInit() {
this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
}

updateChart(data: Array<IOee>) {
//Logic here
}
}

最佳答案

首先注入(inject)Injector

 import { Injector } from '@angular/core';
import { getTestBed } from '@angular/core/testing';

创建服务变量(位于组件变量下方)

let service : CellService;
let injector : Injector;

在测试床进程之后注入(inject)它(就在组件实例下方)

injector = getTestBed();
service = injector.get(CellService)

现在你可以监视它了

spyOn(service, 'YourMethod').and.returnValue({ subscribe: () => {} });

如果您的工作描述部分代码有任何困惑,请告诉我

describe('Oee24Component', () => {
let component: any;
let fixture: ComponentFixture<Oee24Component>;
let injector: Injector;
let service: CellService;


beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Oee24Component],
providers: [{ provide: CellService, useValue: fakeCellService }]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(Oee24Component);
component = fixture.componentInstance;
injector = getTestBed();
service = injector.get(CellService)
fixture.detectChanges();
spyOn(service, 'getCellOEE').and.returnValue({ subscribe : () => {} });
});

it('should get cell oee on init', () => {
component.ngOnInit();
expect(service.getCellOEE).toHaveBeenCalled();
});
});

关于javascript - Jasmine 函数 Spy 不适用于 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43123021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com