我正在尝试用我的角度5应用程序使用量角器制作一些黄瓜测试用例。我不确定如何模拟我的服务。我希望我的组件在从它们调用函数时使用我的模拟服务。
这是一个简单的例子:
foobar.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from '../../../services/test.service';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
myDataObject: any;
constructor(private testService: TestService) {
this.myDataObject = this.testService.getTestObject();
}
ngOnInit() {}
}
test.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
constructor() {}
getTestObject(): any {
return {
'foo': 1,
'bar': 2
}
}
}
foobar.step.ts
import { browser, element, by } from 'protractor';
const { Before, Given, When, Then, defineSupportCode } = require('cucumber');
const chai = require('chai').use(require('chai-as-promised'));
const expect = chai.expect;
defineSupportCode(function ({ setDefaultTimeout }) {
setDefaultTimeout(120 * 1000);
});
Before(() => {
// Setup a mock service and use the values I set here. In this case I would want to mock out whatever TestService.getTestObject() returns and have my component use the mock values.
}
Given('some test here', (next) => {
next();
});
When('the page loads', (next) => {
browser.get('/').then(function () {
next();
});
});
Then('some text here', (next) => {
// Use mock values and create expect statement to see if something was shown on the page.
});
我想这样做的原因是因为我的模板依赖于我的服务返回的对象的值来确定是否应该显示某些div
块。
如何模拟我的服务并让我的组件在我的量角器测试中使用它?任何帮助,将不胜感激。谢谢!
答案 0 :(得分:2)
如评论中所述,您不会在E2E测试中使用TestBed来模拟服务,但您可以在运行测试时切换环境,从而提供完整的模拟服务:
@NgModule({
imports: [...],
providers: [
{
provide: AbstractService,
useClass: (environment.mockService ? TestService : RealService) // both extend AbstractService
}
],
declarations: ...,
exports: ...
})
export class MyModule {}
并在package.json中(您需要使用自己的文件设置环境并将其连接到angular-cli.json中)...
"test": "ng test --env=unit-test",