Angular Jasmine Integration Test with service usin

2019-02-16 03:35发布

[Angular version: 2.4.5]

I'm attempting to write an Angular integration component unit test that contains a service that leverages the built-in Angular HTTP library. I cannot get my Service class to instantiate though: either the Service is undefined or I get "Error: Cannot resolve all parameters for 'RequestOptions'(?)".

I understand that typically you'd mock the backend (have successfully done that in other unit tests) or use Protractor. Other SO questions reference Angular 1 or have answers that just don't seem to work. Starting code:

    @Injectable()
    export class ProjectService {
        projectFeature: IProjectFeature;

        constructor(private http: Http) { }

        getProjects(): Observable<IProjects> {
        return this.http.get("/api/Projects")
            .map((response: Response) => response.json() || {})
            .catch(this.handleError);
         }
    }

     // Jasmine spec file:   
        beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                Http,
                ProjectService,  // service that leverages HTTP
                ConnectionBackend
                //RequestOptions  // removed b/c otherwise can't find parameters error happens
            ],
            imports: [
               HttpModule
            ] 
        });
    }));

    it('sample test', async(() => {
        var projectService = TestBed.get(ProjectService);
        var comp = new ProjectComponent(projectService);
        comp.ngOnInit();  // internally, calls projectService.getProjects()
        expect(comp.projects[0].name).toEqual("Sample Project Name");
    })); 

1条回答
女痞
2楼-- · 2019-02-16 04:19

HttpModule module should be provided in TestBed module configuration. After that, Http performs real XHR requests, no extra actions needed, a demo:

  beforeEach(() => {
    TestBed.resetTestEnvironment();

    TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );

    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ]
    });

  });

  it('should do XHR', async(inject([Http], (http) => {
    http.get('test.json').subscribe(res => {
      expect(res.json()).toBe(1);
    });
  })));
查看更多
登录 后发表回答