简体   繁体   English

使用Angular 7进行单元测试

[英]Unit Testing with Angular 7

I am trying to write unit test for this angular script: 我正在尝试为此角度脚本编写单元测试:

export class DataService {
  private csrfToken: string = '';

  private isContentShow: BehaviorSubject<boolean> = new BehaviorSubject(true);

  constructor(private http: HttpClient, private cookieService: CookieService) {
    this.token = this.cookieService.get('token');
  }

  public createData(data: Data) {
    try {
       this.http.post(  url,
                        data,
                        {
                          headers: new HttpHeaders({
                              'Content-Type':  'application/json',
                              'Authorization': this.token
                          })
                        })
      .subscribe(
        data => {
                this.isContentShow.next(true);
                },
        err => {
        this.showError();
        },
        () => console.log('Request Complete')
      );
      return true;
    } catch {
      this.showError();
      }
    }

  public getIsContentShow(): Observable<boolean> {
    return this.isContentShow.asObservable();
  } 
}

The test that I had so far and its running as expected. 到目前为止,我进行的测试及其运行符合预期。

 it('#getIsContentShow should return value from observable',
    (done: DoneFn) => {
    service.getIsContentShow().subscribe(value => {
      expect(value).toBe(true);
      done();
    });
  });

However I am trying to write the test for createData() function 但是我正在尝试为createData()函数编写测试

I am able to mock the HttpClient using HttpClientTestingModule however I don't know how to handdle the CookieService and token ? 我可以嘲笑HttpClient使用HttpClientTestingModule但我不知道该怎么handdle的CookieService和令牌?

Thanks 谢谢

You can use spies to spy on the cookieService get method. 您可以使用间谍来监视cookieService的get方法。 This way, you can write your unit test to test the combinations of returns you say the cookieService can provide. 这样,您可以编写单元测试来测试您说cookieService可以提供的收益组合。

This link says that you can spy on the prototype of the method in order to handle it how you like in the constructor. 该链接表示,您可以窥探该方法的原型,以便在构造函数中以自己喜欢的方式对其进行处理。

it(
  "should call #getGeneralStats in the constructor",
  inject(
    [CookieService, HttpClient],
    (cookieService: CookieService, http: HttpClient) => {
      let mySpy = spyOn(cookieService, 'get').and.returnValue(<your value>);

      dataService = new DataService(http, cookieService);

      expect(mySpy).toHaveBeenCalled();
    }
  )
);

For you, this may depend on how you're writing your tests. 对于您来说,这可能取决于您如何编写测试。 The example shows the service being instantiated like new ServiceName , but it's also possible to use dependency injection to get the service. 该示例显示了像new ServiceName一样实例化的new ServiceName ,但是也可以使用依赖注入来获取服务。 If you're using DI for the service you are testing, I'd have to research more how to do this (others please feel free to add your answer if you know how to do that)! 如果您将DI用于要测试的服务,那么我将不得不研究更多方法(如果您知道如何做,请随时添加答案)!

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

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