Angular 测试未调用预期导致 "Spec has no expectation"

Angular testing not invoking expectation resulting to "Spec has no expectation"

我有向我的后端发出 HTTP 调用的服务,我正在尝试测试它是否会得到用户响应,在 运行 测试时我得到 Spec has no expectation 即使我在订阅中有一个。所有这些测试都通过了,但 2 的输出为 SPEC HAS NO EXPECTATION

这是我的代码:

describe('Auth Service Testing', () => {
  let httpClientSpy: { get: jasmine.Spy };
  let authServ: AuthService;
  let authAct: AuthActions;
  let userAct: UserActions;
  let checkoutAct: CheckoutActions;
  let productAct: ProductActions;
  let store: Store<any>;
  let localStorageServ: LocalStorageService;
  let authResponse;
  const expectedUserResponse = {
    users: [],
    count: 25,
    current_page: 1,
    pages: 2
  };

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    authServ = new AuthService(
      <any>httpClientSpy,
      authAct,
      userAct,
      checkoutAct,
      productAct,
      store,
      localStorageServ
    );
  });

  it('should get users response', () => {
    httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));

    authServ.authorized().subscribe((users) => {
      authResponse = users;
      expect(users).toEqual(jasmine.objectContaining({ users: [] }));
    });

  });

  it('should equal to expected users response', () => {
    expect(authResponse).toEqual(expectedUserResponse);
  });

  it('should return null if theres an error', () => {
    httpClientSpy.get.and.returnValue(asyncError(expectedUserResponse));
    authServ
      .authorized()
      .subscribe(() => {}, (error) => expect(error).toBe(null));
  });
});

此外,我遵循了 angular HTTP 测试指南 angular test 我想知道这是错误还是其他原因。

业力结果:

Auth Service Testing
SPEC HAS NO EXPECTATIONS should return null if there's an error
SPEC HAS NO EXPECTATIONS should get users response
should equal to expected users response

更新

缺少的代码是这个 expect(httpClientSpy.get.calls.count()).toBe(1); 这很奇怪,我认为这个调用发出了一个 http get 请求 httpClientSpy.get.and.returnValue(asyncError(expectedUserResponse));

但是在指南的错误测试中,他们没有这个。有人可以阐明这一点吗?

来自朝鲜的爱。 <3

使用订阅对可观察对象进行单元测试真的很困难。在许多边缘情况下,单元测试会通过,但本应失败。即使您将 done() 回调与 finiazlier 或错误处理程序一起使用。

只要 observable 仅发出 一个 预期结果,那么您应该改用 promise。

  it('should get users response', async () => {
    httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));

    const users = await = authServ.authorized().toPromise();

    expect(users).toEqual(jasmine.objectContaining({ users: [] }));
  });

每当一个 observable 发出多个值时,您就可以转换为数组并仍然使用 promise。

  it('should get users response', async () => {
    httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));

    const users = await = authServ.authorized().pipe(
        toArray()
    ).toPromise();

    expect(users).toEqual(jasmine.objectContaining([{ users: [] }]));
  });

toPromise()的优点是它总是解析。即使 observable 没有发出任何值,并且如果在 observable 中抛出任何未捕获的错误,它也无法通过单元测试。