繁体   English   中英

在 Angular Karma Jasmine 测试中模拟服务

[英]Mocking A Service in angular Karma Jasmine Testing

我试图通过将服务添加到规范中的提供者数组并使用它的函数添加 createSpyObj 来模拟服务,但出现以下错误:

从源 'http:localhost:9876' 在 ''ng://DynamicTestModule/mycomponent_Host.ngfactory.js' 访问 XMLHttpRequest

我究竟做错了什么?

// .... 导入服务

mockService = jasmine.createSpyObj(['function1'])
testBed.configureTestingModule({
  providers:[{
      {provide: myService, useValue: mockService}
  }]
}).compileComponents()

您创建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将 then 插入到组件中。 你可以参考我的这篇文章来了解这个想法

假设您有一个名为SharedService的服务要测试

// 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();
    });

我要做的是提供服务,但利用 Angular 的HttpClientTestingModuleHttpTestingController来配置您想要的每个单元测试的单独 http 响应。

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [],
        providers: [SharedService]
    }).compileComponents();
}));

一旦您提供了服务,您就可以访问其中的所有内容。

从本质上讲,您可以为您编写的每个单独测试创建模拟响应并通过测试套件“刷新”它们。 这允许为每个测试配置 HTTP 响应,而不是为您提供整个服务测试套件一个响应。

下面是一个例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM