单元测试与 KarmaJasmine

离子中的单元测试与任何角度应用程序中的相同。

我们将使用一些框架来执行此操作。

Karma - 运行测试的框架

Jasmine - 编写测试的框架

PhantomJS - 一个在没有浏览器的情况下运行 javascript 的应用程序

首先让我们安装一切,所以请确保你的 package.json 在 dev 依赖项中包含这些行。我觉得重要的是要注意,dev 依赖项根本不会影响你的应用程序,只是为了帮助开发人员。

"@ionic/app-scripts": "1.1.4",
"@ionic/cli-build-ionic-angular": "0.0.3",
"@ionic/cli-plugin-cordova": "0.0.9",
"@types/jasmine": "^2.5.41",
"@types/node": "^7.0.8",
"angular2-template-loader": "^0.6.2",
"html-loader": "^0.4.5",
"jasmine": "^2.5.3",
"karma": "^1.5.0",
"karma-chrome-launcher": "^2.0.0",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.3",
"null-loader": "^0.1.1",
"ts-loader": "^2.0.3",
"typescript": "2.0.9"

稍微回顾一下包裹

"angular2-template-loader": "^0.6.2", - will load and compile the angular2 html files.

"ts-loader": "^2.0.3", - will compile the actual typescript files

"null-loader": "^0.1.1", - will not load the assets that will be missing, such as fonts and images. We are testing, not image lurking.

我们还应该将此脚本添加到 package.json 脚本中:

"test": "karma start ./test-config/karma.conf.js"

另请注意,在 tsconfig 中,你要从编译中排除 spec.ts 文件:

 "exclude": [
    "node_modules",
    "src/**/*.spec.ts"
  ],

好的,现在让我们采取实际的测试配置。在项目文件夹中创建 test-config 文件夹。 (就像在 package.json 脚本中提到的那样)在文件夹里面创建 3 个文件:

webpack.test.js - 它将告诉 webpack 为测试过程加载哪些文件

var webpack = require('webpack');
var path = require('path');

module.exports = {
  devtool: 'inline-source-map',

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          {
            loader: 'ts-loader'
          } , 'angular2-template-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'null-loader'
      }
    ]
  },

  plugins: [
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      root('./src'), // location of your src
      {} // a map of your routes
    )
  ]
};

function root(localPath) {
  return path.resolve(__dirname, localPath);
}

karma-test-shim.js - 将加载角度相关库,例如区域和测试库,以及配置模块进行测试。

Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

var appContext = require.context('../src', true, /\.spec\.ts/);

appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

karma.conf.js - 定义如何使用业力测试的配置。在这里,你可以从 Chrome 切换到 PhantomJS,以使此过程在其他方面不可见且更快。

var webpackConfig = require('./webpack.test.js');

module.exports = function (config) {
  var _config = {
    basePath: '',

    frameworks: ['jasmine'],

    files: [
      {pattern: './karma-test-shim.js', watched: true}
    ],

    preprocessors: {
      './karma-test-shim.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      stats: 'errors-only'
    },

    webpackServer: {
      noInfo: true
    },

    browserConsoleLogOptions: {
      level: 'log',
      format: '%b %T: %m',
      terminal: true
    },

    reporters: ['kjhtml', 'dots'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  };

  config.set(_config);
};

现在我们配置了一切,让我们写一些实际的测试。在本例中,我们将编写一个 app.component 规范文件。如果你想查看页面的测试而不是主要组件,可以在此处查看: https//github.com/driftyco/ionic-unit-testing-example/blob/master/src/pages/page1/page1。spec.ts

我们首先需要做的是测试我们的构造函数。这将创建并运行 app.component 的构造函数

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyApp],
      imports: [
        IonicModule.forRoot(MyApp)
      ],
      providers: [
        StatusBar,
        SplashScreen
      ]
    })
  }));

声明将包括我们的主要离子应用程序。Imports 将进行此测试所需的导入。不是一切。

提供程序将包含注入构造函数但不属于导入的内容。例如,app.component 注入 Platform 服务,但由于它是 IonicModule 的一部分,因此无需在提供程序中提及它。

对于下一个测试,我们需要获取组件的实例:

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

接下来几个测试,看看一切都井然有序:

  it ('should be created', () => {
    expect(component instanceof MyApp).toBe(true);
  });

  it ('should have two pages', () => {
    expect(component.pages.length).toBe(2);
  });

所以最后我们会有这样的事情:

import { async, TestBed } from '@angular/core/testing';
import { IonicModule } from 'ionic-angular';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { MyApp } from './app.component';

describe('MyApp Component', () => {
  let fixture;
  let component;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyApp],
      imports: [
        IonicModule.forRoot(MyApp)
      ],
      providers: [
        StatusBar,
        SplashScreen
      ]
    })
  }));

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

  it ('should be created', () => {
    expect(component instanceof MyApp).toBe(true);
  });

  it ('should have two pages', () => {
    expect(component.pages.length).toBe(2);
  });

});

运行测试

npm run test

对于基本测试而言,这就是它。有一些方法可以简化测试编写,例如编写自己的 TestBed 并在测试中继承,这可能会帮助你从长远来看。