顯示具有 angular2 unit test 標籤的文章。 顯示所有文章
顯示具有 angular2 unit test 標籤的文章。 顯示所有文章

2018年2月6日 星期二

Ionic3 + FCM (推播)

Firebase 推出FCM 目的將用來取代GCM,雖然GCM 仍然不滅,但我們先來嘗鮮看看,連推播的介面都已經設計好了,只要簡單幾行Code就可以完成推播的功能,廢話不說,就先看示範吧。

一、   下戴必要的套件


二、   設定Config.XML

修改widget id的名稱,因為要對應到FCM準備要推播的應用程式名稱,所以如果不一致就無法接收推播了喔!!!  很重要

三、注入model

import { FCM } from '@ionic-native/fcm';
@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    FCM
  ]
})
export class AppModule {}
FCM 推播的物件是要被注入Provider ,如果沒注入 就會失敗囉~

四、呼叫FCM 的實作演練
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FCM } from '@ionic-native/fcm';   //注入FCM 到Constructor
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private fcm: FCM) {
  
  fcm.subscribeToTopic('marketing');
 
//取得FCM 的token
  fcm.getToken().then(token => {
    alert("getToken")
  })

 //取得FCM 的推播訊息
   fcm.onNotification().subscribe(data => {
    if (data.wasTapped) { //取得背景監聽
      alert("message in background!");
    } else {
      alert("message in front! "); //前景
      alert(JSON.stringify(data)); //取得推播資訊
    };
  })

  //取消推播
  fcm.unsubscribeFromTopic('marketing');

  }

}

根據Ionic的官方文件 需要訂閱名稱,位置放在constructor fcm.subscribeToTopic('marketing');

在結束時就要將訂閱名稱取消…。
fcm.unsubscribeFromTopic('marketing');

五、設定推播內容

Project OverView à 新增其他應用程式 (config.xml的 widget id)



















點選新增訊息



選擇剛剛新增 應用程式











設定前景資料(當應用程式是開啟)

接收的推播


2016年6月26日 星期日

Angular2 + Ionic2

最近的angular2的釋出時,不曉得大家有沒有發現ionic也推出適合 angular2,所以當然先來試用看看ionic2, 似乎ionic2 為了在手持裝置上加了不少的元件,大家再來一起研究看看吧~

一、建立ionic 2 的語法

npm install -g ionic@beta
//開啟ionic2的新專案【cutePuppyPics】
ionic start cutePuppyPics –v2  

//執行ionic2
cd cutePuppyPics 
ionic serve                


建立ionic 專案 預設為tabs為範本

二、開始撰寫ionic2的angular2
示範在contact.html頁面中,增加navigation (瀏覽頁面-->返回頁面)的功能

contact.html
<ion-navbar *navbar hideBackButton>
<ion-title>
Contact
</ion-title>
</ion-navbar>

<ion-content>
<ion-list>
<ion-item *ngFor="let item of items" (click)="openNavDetailsPage(item)">
<ion-thumbnail item-left>
<img src="img/{{item.image}}">
</ion-thumbnail>
<h2>{{item.title}}</h2>
<p>Hayao Miyazaki • 1988</p>
<button clear item-right>View</button>
</ion-item>
</ion-list>
</ion-content>

因為我的來源是items,所以要先設定list的範本樣式和點擊的範圍,點擊整列就能進入到下一頁,所以在<ion-item> 加了click事件,接下來就要實作click的angular 語法囉~

contact.ts
import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {ItemService} from './item_services';
import { viewItem } from './view_item';

@Component({
templateUrl: 'build/pages/contact/navigation-details.html', //呈現navigation 的下一頁面
})
class NavigationDetailsPage {
item;
constructor(params: NavParams) {
this.item = params.data.item; //傳遞過來的參數
console.log(NavParams);
}
}

@Component({
templateUrl: 'build/pages/contact/contact.html',
providers: [ItemService] //呼叫ItemSerivce, 目的抽出資料層
})
export class ContactPage {
private items;
//預設為先執行的函式,navController是預設先,作者還另外注入itemService
constructor(public nav: NavController, private itemService: ItemService) {
this.itemService.getItems().then(cItems => this.items = cItems);
}
//外部點選click事件
openNavDetailsPage(viewItem) {
this.nav.push(NavigationDetailsPage, { item: viewItem }); //將頁面轉換到navigationDetailPage
}
}

這樣就簡單的完成有導覽式navigation的行為,點選資料列,進入到下一頁後,還能返回上一頁的一連串的動作。




下次再介紹其他的控件吧~ 先簡單略過囉!


三、安裝單元測試的套件

當案件越來越龐大時,單一測試就越來越重要囉… 所以angular也有推出自已的unit test套件,所以結合ionic2 一起來試用看看…

npm install karma karma-jasmine karma-phantomjs-launcher --save-dev
npm install -g karma-cli
npm install angular-mock --save-dev
kama init my.conf.js

執行的過程…會出現一連串的詢問視窗如下所示
which framwork do you want to use?
>jasmine : 就按ENTER

do you want to use require.js?
>no: 按ENTER

接下來不論它問是什麼…按下ENTER 就對了… 預設為主

重點在後面…你要修改kama.config.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'browserify'],


// list of files / patterns to load in the browser
files: [
'node_modules/es6-shim/es6-shim.js', // TypeError: undefined is not a constructor (evaluating 'new exports.Map()')
'node_modules/reflect-metadata/Reflect.js', // 'Uncaught reflect-metadata shim is required when using class decorators'
'node_modules/zone.js/dist/zone.js', // Zone.js dependencies (Zone undefined)
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
'app/**/*.spec.ts',
{ pattern: 'node_modules/reflect-metadata/Reflect.js.map', included: false, served: true }, // 404 on the same
{ pattern: 'www/build/**/*.html', included: false },
],

// list of files to exclude
exclude: [
'node_modules/angular2/**/*_spec.js',
'node_modules/ionic-angular/**/*spec*'
],

browserify: {
debug: true,
transform: [
['browserify-istanbul', {
instrumenter: require('isparta'),
ignore: ['**/*.spec.ts', '**/*.d.ts'],
}]
],
plugin: [
['tsify']
]
},

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.ts': ['browserify']
},


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],

// web server port
port: 9876,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,

// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}

以下的設定檔中,需要修改的部份是【files】,【browserify】,【frameworks】,【exclude】,我也還不確認為何要這麼設定… 總之按照google大神查出來的樣本,有人是這麼設定的,就能run出測試結果囉。

修改pack.json
{
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"es6-shim": "^0.35.0",
"ionic-angular": "2.0.0-beta.9",
"ionic-native": "1.2.4",
"ionicons": "3.0.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12"
},
"devDependencies": {
"angular-mock": "^1.0.0",
"browserify": "13.0.0",
"browserify-istanbul": "2.0.0",
"del": "2.2.0",
"gulp": "3.9.1",
"gulp-watch": "4.3.5",
"ionic-gulp-browserify-typescript": "^1.1.0",
"ionic-gulp-fonts-copy": "^1.0.0",
"ionic-gulp-html-copy": "^1.0.0",
"ionic-gulp-sass-build": "^1.0.0",
"ionic-gulp-scripts-copy": "^2.0.0",
"isparta": "4.0.0",
"jasmine-core": "^2.4.1",
"karma": "^0.13.22",
"karma-browserify": "5.0.5",
"karma-chrome-launcher": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-phantomjs-launcher": "^1.0.0",
"run-sequence": "1.1.5",
"tsify": "0.16.0"
},
"name": "cutepuppypics",
"description": "cutePuppyPics: An Ionic project",
"cordovaPlugins": [
"cordova-plugin-device",
"cordova-plugin-console",
"cordova-plugin-whitelist",
"cordova-plugin-splashscreen",
"cordova-plugin-statusbar",
"ionic-plugin-keyboard"
],
"cordovaPlatforms": [],
"version": "1.0.0",
"main": "gulpfile.js",
"scripts": {
"test": "karma start karma.conf.js"
},
"author": "",
"license": "ISC"
}
相依性的【devDependencies】需要加上karma等相關套件,【scripts】加上test的相關設定

下指令>npm install //下戴相依性的套件
參考自:

四、開始撰寫測試程式
app的資料夾下新增【app.spec.ts】的檔案
app.spec.ts
import {beforeEachProviders, it, describe, expect, inject} from '@angular/core/testing';
import {ItemService} from "./pages/contact/item_services";
describe('test ItemService return', () => {
beforeEachProviders(() => [ItemService]);
it('should return kitty', inject([ItemService], (mockItem) => {
let result = mockItem.getItems();
expect(result.__zone_symbol__value[0].title).toEqual("kitty");
}
));
})
Ps:如果要顯示回傳的資料,要呼叫__zone_symbol__value的屬性

>npm test //執行測試


預期結果: