问题描述
我创建了一个运行Stack/Jasmine加载程序的StackBlitz ,因此您可以查看测试通过/失败.
I've created a StackBlitz with the karma/jasmine loader running so you can see the test pass/fail.
应用程序可以正常工作.
The application is working as it should.
我的测试应该可以并且可以通过,但是我在使用模拟服务而不是对createspyobject
启用的适当服务时遇到了一个奇怪的错误.
My tests should be ok and will pass, however I'm getting a strange error with using a mockservice instead of the proper service to createspyobject
on.
component.ts
getReportFunc(): void {
this.reportService.getReport(this.urn).subscribe(selectedReport => {
this.model = selectedReport;
});
}
对服务的简单调用以获取"getReport".我将添加一个测试以检查该报告是否已被调用.但是由于这个问题而不能.
Simple call to a service to fetch "getReport". I will add a test to check that the report has been called. however cant because of this issue.
spec.ts
describe("SearchComponent", () => {
let component: SearchComponent;
let fixture: ComponentFixture<SearchComponent>;
let mockReportService;
beforeEach(async(() => {
mockReportService = jasmine.createSpyObj(['getReport']);
TestBed.configureTestingModule({
declarations: [SearchComponent],
providers: [
//ReportService,
{ provide: ReportService, useValue: mockReportService },
...
问题在于仅使用ReportService
的{ provide: ReportService, useValue: mockReportService }
可以正常运行,但这意味着我无法运行我的测试之一.我想创建一个间谍对象mockReportService = jasmine.createSpyObj(['getReport']);
.
The issue is with { provide: ReportService, useValue: mockReportService }
using just ReportService
will run fine but it means I cant run one of my tests. I want to create a spy object mockReportService = jasmine.createSpyObj(['getReport']);
.
您将在 StackBlitz 是那个TypeError: Cannot read property 'subscribe' of undefined
.
如果有人可以帮助我使它与模拟服务一起运行,以便我可以测试getReport订阅功能,我将不胜感激.
If somebody can help me getting this to run with a mockservice so I can test the getReport subscribe function I would be most grateful.
推荐答案
问题来自jasmine.createSpyObj
的误用.您有2个选择:
The problem comes from a misuse of jasmine.createSpyObj
You have 2 options :
- 以正确的方式使用
jasmine.createSpyObj
:
// Note the first arg, you were missing it
mockReportService = jasmine.createSpyObj(ReportService, ['getReport']);
// Then, explain what to do with it :
beforeEach(() => {
[...]
// When called, make it return an Observable so that the call to subscribe() succeeds
mockReportService.getReport.and.returnValue(of({}));
fixture.detectChanges();
});
- 不要使用间谍
当然,间谍很整洁,但是仅当您想在不同的单元测试期间更改返回的值时,它们才有用.如果您只需要始终返回一个值,那么无论哪个,您都可以选择像这样的硬编码对象:
Sure, spies are neat but they are useful only if you want to change the returned values during the different unit tests. If you just need to always return a value, no matter which, you can opt for a hardcoded object like this :
const mockReportService = {
getReport: () => of({})
}
providers: [
{ provide: ReportService, useValue: mockReportService },
这篇关于Jasmine单元测试中的MockService的UseValue导致测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!