Error "Variable is used before being assigned" in an Angular unit test although it's like in an article

huangapple go评论74阅读模式
英文:

Error "Variable is used before being assigned" in an Angular unit test although it's like in an article

问题

以下是代码部分的中文翻译:

我是 Angular 单元测试的新手,尝试测试 API 访问。

这是我的代码:
```typescript
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { JwtHelperService, JWT_OPTIONS } from '@auth0/angular-jwt';

import { AuthService } from '../../services/auth.service';
import { UserService } from '../../services/user.service';
import { WorkService } from '../../services/work.service';
import { ErrorToLogService } from '../../services/errorToLog.service';

import { FooterComponent } from './footer.component';

describe('FooterComponent', () => {
  let component: FooterComponent;
  let fixture: ComponentFixture<FooterComponent>;
  let httpController: HttpTestingController;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        AuthService,
        UserService,
        WorkService,
        ErrorToLogService,
        JwtHelperService,
        { provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
      ],
      declarations: [FooterComponent]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(FooterComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    httpController = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    TestBed.resetTestingModule();
  });

  it('应该创建', () => {
    expect(component).toBeTruthy();
  });

  it('检查 API 返回网站管理员',  () =>  {
    let res: string;
    component.getUserService().getWebmasterEmail().subscribe(
      data => res = data,
    );

    const req = httpController.expectOne({
      method: 'GET',
      url: `/api/getWebmasterEmail`,
    });

    req.flush("toto");
    expect(res).toEqual("toto");
  });
});

测试 检查 API 返回网站管理员 无法编译,因为出现了变量 'res' 在分配之前使用的错误。

我有点理解,但我看不出为什么它在这篇文章中的“Angular Service Unit Testing Example with HttpClient” 部分(测试“应该返回数据”)中能够更好地工作。

有人能解释这个问题吗?

英文:

I'm new at Angular unit tests and try to test an API access.

Here's my code:

import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;
import { HttpClientTestingModule, HttpTestingController } from &#39;@angular/common/http/testing&#39;
import { JwtHelperService, JWT_OPTIONS } from &#39;@auth0/angular-jwt&#39;

import { AuthService } from &#39;../../services/auth.service&#39;
import { UserService } from &#39;../../services/user.service&#39;
import { WorkService } from &#39;../../services/work.service&#39;
import { ErrorToLogService } from &#39;../../services/errorToLog.service&#39;

import { FooterComponent } from &#39;./footer.component&#39;

describe(&#39;FooterComponent&#39;, () =&gt; {
  let component: FooterComponent
  let fixture: ComponentFixture&lt;FooterComponent&gt;
  let httpController: HttpTestingController

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        AuthService,
        UserService,
        WorkService,
        ErrorToLogService,
        JwtHelperService,
        { provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
      ],
      declarations: [ FooterComponent ]
    })
    .compileComponents()
  })

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(FooterComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
    httpController = TestBed.inject(HttpTestingController)
  })

  afterEach(() =&gt; {
    TestBed.resetTestingModule()
  })

  it(&#39;should create&#39;, () =&gt; {
    expect(component).toBeTruthy()
  })

  it(&#39;Check API returns the webmaster&#39;,  () =&gt;  {
    let res: string
    component.getUserService().getWebmasterEmail().subscribe(
      data =&gt; res = data,
    )

    const req = httpController.expectOne({
      method: &#39;GET&#39;,
      url: `/api/getWebmasterEmail`,
    })

    req.flush(&quot;toto&quot;)
    expect(res).toEqual(&quot;toto&quot;)
  })
})

The test Check API returns the webmaster doesn't compile because Variable &#39;res&#39; is used before being assigned.

I kind of understand but I can't see why it would work better in the paragraph "Angular Service Unit Testing Example with HttpClient" of this article (test "should return data").

Anyone to shed light on this issue?

答案1

得分: 2

req.flush() 表示你正在解决这个 promise。你仍然需要将你的 expect 移到 promise 内部。

it('检查 API 返回网站管理员', () => {
  let res: string;
  component.getUserService().getWebmasterEmail().subscribe(
    data => {
      res = data;
      expect(res).toEqual("toto");
    }
  );

  const req = httpController.expectOne({
    method: 'GET',
    url: `/api/getWebmasterEmail`,
  });

  req.flush("toto");
})
英文:

req.flush() just means that you are resolving the promise. you'll still need to move your expect to within the promise.

it(&#39;Check API returns the webmaster&#39;,  () =&gt;  {
    let res: string
    component.getUserService().getWebmasterEmail().subscribe(
      data =&gt; {
      res = data,
      expect(res).toEqual(&quot;toto&quot;);
    }
    )

    const req = httpController.expectOne({
      method: &#39;GET&#39;,
      url: `/api/getWebmasterEmail`,
    })

    req.flush(&quot;toto&quot;)
  })

huangapple
  • 本文由 发表于 2023年2月27日 03:49:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定