前端测试框架

Karma

karma跑测试是启动一个浏览器,它访问不了文件,所以如果需要文件,就要启动服务,通过http请求获取文件内容。

Jest

安装

Jest 是跑测试的一个框架,比起angular自带的karma要快的多。

  • npm install jest jest-preset-angular --dev
  • 在package.json添加入口:
"jest": {
  "preset": "jest-preset-angular",
  "setupTestFrameworkScriptFile": "/src/setupJest.ts"
}

setupJest.ts

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

jestGlobalMocks.ts

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(window, 'getComputedStyle', {
  value: () => ['-webkit-appearance']
});

Object.defineProperty(window, 'URL', {
  value: {
    createObjectURL: () => {}
  }
});

  • 添加命令
"test": "jest",
"test:watch": "jest --watch",

具体配置可以参考testing-angular-faster-jest

遇到的坑

可以直接读文件,但是不能直接用文件地址,这样是读不到文件的,会报no such file or directory error。例如:'../XXX/XXX'
而是要用path
import * as fs from 'fs';
import * as path from 'path';
const BASE_URL = path.join(__dirname, '../XXX/XXX/');
fs.readFileSync(BASE_URL + jsonName)

你可能感兴趣的:(前端测试框架)