首页 > 解决方案 > 如何解决 Angular 7 上的 jest 问题?

问题描述

当我在我的角度 7 上运行测试时,我收到了这个错误

console.error node_modules/jest-environment-jsdom-thirteen/node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Error: connect ECONNREFUSED 127.0.0.1:80
          at Object.dispatchError (D:\Subin\PROJECTS\angular-project\node_modules\jest-environment-jsdom-thirteen\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:60:19)
          at Request.client.on.err (D:\Subin\PROJECTS\angular-project\node_modules\jest-environment-jsdom-thirteen\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:674:20)
          at emitOne (events.js:121:20)
          at Request.emit (events.js:211:7)
          at Request.onRequestError (D:\Subin\PROJECTS\angular-project\node_modules\request\request.js:881:8)
          at emitOne (events.js:116:13)
          at ClientRequest.emit (events.js:211:7)
          at Socket.socketErrorListener (_http_client.js:387:9)
          at emitOne (events.js:116:13)
          at Socket.emit (events.js:211:7) undefined

有没有什么办法解决这一问题?

我的 setupJest.ts

import 'jest-preset-angular';

Object.defineProperty(window, 'CSS', {value: null});
Object.defineProperty(document, 'doctype', {
  value: '<!DOCTYPE html>'
});
Object.defineProperty(window, 'getComputedStyle', {
  value: () => {
    return {
      display: 'none',
      appearance: ['-webkit-appearance']
    };
  }
});
/**
 * ISSUE: https://github.com/angular/material2/issues/7101
 * Workaround for JSDOM missing transform property
 */
Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});

包.json

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "jest",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
"jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": [
      "<rootDir>/setupJest.ts"
    ],
    "globals": {
      "ts-jest": {
        "diagnostics": false
      }
    }
  },

我从https://angular.io/guide/testing读到这个

当您运行 CLI ng test 命令时,这不是问题,因为它会在运行测试之前编译应用程序。

但是,如果您在非 CLI 环境中运行测试,则此组件的测试可能会失败

我认为这与我在非 CLI 环境中运行测试有关。

我试过的:

  1. 尝试使用 @angular-builders/jest 在 CLI 环境中运行测试
  2. 试图覆盖我的应用程序组件上的外部文件

我的应用组件规范

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AppComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  test('should create the app', async(() => {
    expect(component).toBeTruthy();
  }));
});

标签: angularunit-testingjestjs

解决方案


推荐阅读