简体   繁体   English

Angular 如果服务有构造函数,Jest 服务测试将失败

[英]Angular Jest service test fail if service has a contructor

Angular test fail when i try to test service that contains contructor. Angular 当我尝试测试包含构造函数的服务时测试失败。 No matter if constructor has dependencies or it's empty.不管构造函数是否有依赖关系或者它是空的。

Hi, I have an issue with testing angular app using jest.您好,我在使用 jest 测试 angular 应用程序时遇到问题。 When I try to test my service i receive error:当我尝试测试我的服务时,我收到错误消息:

 <dirToProject>\src\app\core\services\simple.service.ts:8
        static { this.ctorParameters = () => []; }
               ^

    SyntaxError: Unexpected token '{'

    > 1 | import { SimpleService } from './simple.service';
        | ^
      2 | import { TestBed } from '@angular/core/testing';
      3 |
      4 | describe('SimpleService', () => {

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)
      at Object.<anonymous> (src/app/core/services/simple.service.spec.ts:1:1)

Simple service:简单的服务:

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

@Injectable({
  providedIn: 'root'
})
export class SimpleService {

  constructor() { }
}

Test:测试:

import { SimpleService } from './simple.service';
import { TestBed } from '@angular/core/testing';

describe('SimpleService', () => {
  let service: SimpleService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = new SimpleService();
  });

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

Surprisingly this error disappear when i delete constructor from service.令人惊讶的是,当我从服务中删除构造函数时,此错误消失了。 Of course in this example I can remove contructor, but I have to test more complex services with dependencies.当然在这个例子中我可以删除构造器,但我必须测试更复杂的服务与依赖关系。

Do you have any ideas how to solve this?你知道如何解决这个问题吗? Versions: "jest": "^29.5.0", "@angular/core": "^15.2.0"版本: "jest": "^29.5.0", "@angular/core": "^15.2.0"

@Alokin try setting up the tsconfig.ts or tsconfig.spec.ts "target": "ES2020" @Alokin 尝试设置 tsconfig.ts 或 tsconfig.spec.ts "target": "ES2020"

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

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