單元測試與 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 並在測試中繼承,這可能會幫助你從長遠來看。