Joe Kappa
Joe Kappa

Reputation: 49

Unit test fails because of static method

I encountered an interesting problem, there is such a service


import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {
  static generate(url: string, response: string): string[] {
    return [url + response];
  }

  static testField = TestService.generate('aaa', 'vvv');

}


and default spec file


import { TestBed } from '@angular/core/testing';

import { TestService } from './test.service';

fdescribe('TestService', () => {
  let service: TestService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(TestService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

My test fails with this error: Uncaught TypeError: Cannot read properties of undefined (reading 'generate') TypeError: Cannot read properties of undefined (reading 'generate')

but it works if I change my tsconfig:

  1. Delete "useDefineForClassFields": false,

  2. Change "target": "ES2022" to "target": "ES2021"

Any ideas how to fix it without changing "ES2022" to "ES2021"?

P.S. I need to keep testField and generate as static

Upvotes: 1

Views: 281

Answers (0)

Related Questions