【问题标题】:How to mock HTTP Request in Angular?如何在 Angular 中模拟 HTTP 请求?
【发布时间】:2019-11-20 09:24:18
【问题描述】:

我检查了很多文章和答案,但我似乎没有找到正确的方法来模拟我的方法 HTTP Requests。我想独立于backend 测试我的frontend 应用程序。这是我拥有的方法类型:

 private getProfile() {
    this.http
      .get('go/profile/get', {withCredentials: true})
      .subscribe((profile: Profile) => {
        this.user.profile = profile;
        this.updateLineMsgs();
      });
  }

有什么建议吗?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine angular-test


    【解决方案1】:

    通常我用 HttpClientTestingModule 模拟我的 Http 请求:

    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    
    export class TestService {
        constructor(private http: HttpClient) {}
    }
    
    describe('AppInterceptor', () => {
        let service: TestService;
        let httpMock: HttpTestingController;
    
        beforeEach(() => {
            TestBed.configureTestingModule({
                imports: [HttpClientTestingModule],
                providers: [
                    TestService
                ]
            });
            service = TestBed.inject(TestService);
            httpMock = TestBed.inject(HttpTestingController);
        });
    
    ....
    const httpRequest = httpMock.expectOne('any-url');
    

    【讨论】:

      【解决方案2】:

      您始终可以自己创建一个模拟方法并模拟您期望从后端得到的响应。在您的示例中,它可能是

       public static mockGetProfile(){
          const response = JSON.parse(`
           "name": "abc",
           "active": true,
           ...all other json fields that you want
           `);
      
          let obs = new Observable((subscriber) => {
              setTimeout(()=>{
                  subscriber.next(response);
                  subscriber.complete();
              }, 3000);
          });
          return obs;
      }
      

      上述 observable 将在 3 秒或您定义的任何时间段后完成,以某种方式模拟来自后端服务器的响应,这需要一些时间才能可用。

      【讨论】:

        【解决方案3】:

        如果我正确理解您的问题,您想在后端之前创建前端服务,但您仍想使用 Promise / observables。 您可以为此使用of

        import { of } from 'rxjs';
        //emits any number of provided values in sequence
        const source = of(1, 2, 3, 4, 5);
        //output: 1,2,3,4,5
        const subscribe = source.subscribe(val => console.log(val));
        

        来自https://www.learnrxjs.io/operators/creation/of.html

        【讨论】:

          【解决方案4】:

          【讨论】:

            【解决方案5】:

            JSON-Server : https://www.npmjs.com/package/json-server

            它将为您提供一个模拟服务器,其中包含 .json 文件中的所有(GET、POST、PUT、DELETE 等)其余 API...

            【讨论】:

              【解决方案6】:

              您可以将响应json放在asset文件夹中并进行测试。

              例如在 assets/json 下创建一个 test.json 文件并相应地更改您的 url

              private getProfile() {
                  this.http
                    .get('assets/json/test.json', {withCredentials: true})
                    .subscribe((profile: Profile) => {
                      this.user.profile = profile;
                      this.updateLineMsgs();
                    });
                }
              

              您还可以根据环境变量配置要选择的 url,以便在 prod 构建中使用实际 url,而在 dev 中使用虚拟 url。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-05-29
                • 1970-01-01
                • 2020-02-14
                • 2012-07-30
                • 1970-01-01
                相关资源
                最近更新 更多