我正在尝试通过将服务添加到规范中的providers数组并使用其功能添加createSpyObj来模拟服务,但是出现以下错误:
从来源“ http:localhost:9876”访问位于ng://DynamicTestModule/mycomponent_Host.ngfactory.js的XMLHttpRequest
我在做什么错了?
// ....导入服务
mockService = jasmine.createSpyObj(['function1'])
testBed.configureTestingModule({
providers:[{
{provide: myService, useValue: mockService}
}]
}).compileComponents()
答案 0 :(得分:2)
您自己创建spy
的方式是错误的。从错误中看,它似乎与无效导入或其他原因有关。
执行此操作的正确方法是:
describe("UserDetailComponent", () => {
let component: UserDetailComponent;
let fixture: ComponentFixture<UserDetailComponent>;
const mockUserService = jasmine.createSpyObj("UserSvcService", ["getUserDetail"]);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [UserDetailComponent],
providers: [
{ provide: UserSvcService, useValue: mockUserService }
]
}).compileComponents();
}));
....
...
it('should set some values using service',()=>{
mockUserService.getUserDetail.and.returnValue(
of({ data: 'somevalue'})
);
expect(someCondition).toBeDefined();
})
)}
还有其他方法可以使用Stubs
并使用useClass
将其插入组件。 you can refer to this article of mine to get the idea
答案 1 :(得分:1)
只需说您有一个名为// import the service from the desired location, i just indicated with @
import { SharedService } from "@services"
// create an instance inside describe
let sharedService: SharedService
// declare under providers in beforeEach
providers: [SharedService]
// create component and test fixture
fixture = TestBed.createComponent(yourComponentName);
component = fixture.componentInstance;
sharedService = fixture.debugElement.injector.get(SharedService)
// use compileComponents only if you are not using webpack or angular CLI
it('Should call MethodOne - sharedService ==> resolved', () => {
let MockedData = {};
spyOn(sharedService, 'someMethod').and.returnValue(Observable.of(MockedData));
component.MethodOne();
expect(sharedService.someMethod).toHaveBeenCalled();
});
的服务即可进行测试
IF APP_TIME <= ST.APP_START_TIME AND APP_TIME >= ET.APP_END_TIME
答案 2 :(得分:0)
我要做的就是提供服务,但是要利用Angular的 HttpClientTestingModule 和 HttpTestingController 来配置每个单元测试所需的单个http响应。
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
providers: [SharedService]
}).compileComponents();
}));
一旦提供了服务,便可以访问其中的所有内容。
从本质上讲,您可以创建模拟响应,并针对编写的每个测试通过测试套件“刷新”它们。这样可以为每个测试配置HTTP响应,而不是为整个Service测试套件提供一个响应。
这里是一个示例:
it("should return valid response", fakeAsync(
inject([HttpTestingController], (httpMock: HttpTestingController) => {
let mockResponse = { success: true }
httpMock.expectOne('endpoint name here').flush(mockResponse);
fixture.whenStable().then(() => {
//here's your acceptance criteria
});
});
));
这里有一些文档:https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712