带有Angular和Jest的静态文件

时间:2018-10-14 23:37:16

标签: angular karma-runner jestjs

我正在尝试设置一个现有的Angular应用程序以使用Jest。

当我的应用程序在dev或prod中运行时,我的index.html文件需要几个js文件来设置全局var。然后,我有一个引用这些var的配置文件来设置某些内容。

运行Jest时,找不到这些全局var

业力有一个files选项可以解决这个问题。

下面是我的笑话设置

// jest.config.js
module.exports = {
    preset: "jest-preset-angular",
    roots: ['src'],
    setupTestFrameworkScriptFile: "<rootDir>/src/setup-jest.ts"
}

// setup-jest.ts
import 'jest-preset-angular';
import './jestGlobalMocks';


// jestGlobalMocks.ts
global['CSS'] = null;

const mock = () => {
  let storage = {};
  return {
    getItem: key => key in storage ? storage[key] : null,
    setItem: (key, value) => storage[key] = value || '',
    removeItem: key => delete storage[key],
    clear: () => storage = {},
  };
};

Object.defineProperty(window, 'localStorage', {value: mock()});
Object.defineProperty(window, 'sessionStorage', {value: mock()});
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,
    };
  },
});

这是设置全局var的方式。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="HandheldFriendly" content="true">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <base href=".">
        <script src="releaseNotes.js" type="text/javascript"></script>
        <script src="js/languages/inject.en.js" type="text/javascript"></script>
        <script src="js/languages/inject.de.js" type="text/javascript"></script>
        <script src="js/languages/hybrid.inject.en.js" type="text/javascript"></script>
        <script src="js/languages/hybrid.inject.de.js" type="text/javascript"></script>
    </head>
    <body>
        <app-root></app-root>
    </body>
</html>

<script>标签引用了设置var的语言文件。

var HybridInject_en = { ... }
var INJECT_en = { ... }

然后在配置文件中引用...

var windowJS =  new WindowService().nativeWindow;
var HybridInject = windowJS.HybridInject_en; // custom app strings
var INJECT = windowJS.INJECT_en; // copied from main TP web platform

它们也包含在angular.json

    "assets": [
      "src/assets",
      "src/favicon.ico",
      "src/releaseNotes.js",
      "src/js/languages/inject.de.js",
      "src/js/languages/inject.en.js",
      "src/js/languages/hybrid.inject.en.js",
      "src/js/languages/hybrid.inject.de.js"
    ],

无论出于何种原因,当该文件与Jest一起运行时,windowJS上都不存在这些对象。

0 个答案:

没有答案