{"id":2195,"date":"2018-05-09T15:06:42","date_gmt":"2018-05-09T15:06:42","guid":{"rendered":"https:\/\/ionicframework.com\/?p=2195"},"modified":"2018-05-09T15:08:39","modified_gmt":"2018-05-09T15:08:39","slug":"ionic-native-mocks","status":"publish","type":"post","link":"https:\/\/ionic.io\/blog\/ionic-native-mocks","title":{"rendered":"Ionic Native Mocks"},"content":{"rendered":"<p><em>This is a guest post from <a href=\"https:\/\/twitter.com\/ChrisGriffith\">Chris Griffith<\/a>. Chris is UI\/UX engineer, an educator in the Ionic community and author of the Ionic Native Mocks library.<\/em><\/p>\n<p>When you create an Ionic application, often you have need to include a Cordova plugin or two. In fact, several Cordova plugins are included when you generate an Ionic application using any of the Ionic starter templates. These plugins give your Ionic application access to features on our mobile devices that are traditionally unavailable to developers not using native programming languages.<\/p>\n<p><!--more--><\/p>\n<p>Currently, there are over <a href=\"https:\/\/cordova.apache.org\/plugins\/\">3,100 plugins<\/a> registered for Cordova. Of these, the Ionic team has selected around 160 for which to create TypeScript interfaces, Ionic Native, to ease development. Here is the definition:<\/p>\n<blockquote><p>\n  Ionic Native is a curated set of wrappers for Apache Cordova plugins that make adding any native functionality you need to your Ionic mobile application easier.<br \/>\n  Ionic Native provides an interface for all of these plugins that match the Cordova plugin,  wrapping plugin callbacks in a Promise or Observable to make it easy to use plugins with Angular change detection.\n<\/p><\/blockquote>\n<h2>From One Platform to Another<\/h2>\n<p>Once you&#8217;re using Ionic Native, your workflow must now shift from using your computer\u2019s browser to either running in a device simulator or on an actual device. While the Ionic CLI makes some of that process easier, it can still become time consuming.<\/p>\n<p>Here is a real-world example of this issue: I was prototyping a new app where one of the first actions the user would do was scan in a barcode. Adding this functionality is not difficult. I was able to install the plugin and the Ionic Native wrapper, update the <code>app.module.ts<\/code> file and was good to go. But from that point further I was required to run my application on the device. Since there were several more screens to create, I needed to find a way to bypass this \u2018requirement\u2019.<\/p>\n<p>One option would have been to simply comment out that code block and continue developing, but that would require a lot of maintenance; comment the code to develop, remember to uncomment the code before testing or deploying to a device, uncommenting the code again to do more development. Instead of going through that several times a day, I decided to create a mock provider for the barcode scanner plugin that would serve as in interface to the methods and properties of the actual Ionic Native wrapper\u2019s calls to the Cordova plugin. With this mock injected into my application, I can simulate interaction with the barcode scan plugin and continue my local development unimpeded..<\/p>\n<h2>Adding mocks to an App<\/h2>\n<p>From this initial effort, I decided to generate mocks for the entire Ionic Native Library in a collection of mocks called <a href=\"https:\/\/github.com\/chrisgriffith\/ionic-native-mocks\">Ionic Native Mocks<\/a>. To use an Ionic Native Mock run the following command in your terminal to install the appropriate mock for your project:<\/p>\n<pre><code class=\"bash\">npm install @ionic-native-mocks\/&lt;plug-in&gt; --save\n<\/code><\/pre>\n<p>For instance, to install the camera mock:<\/p>\n<pre><code class=\"bash\">npm install @ionic-native-mocks\/camera --save\n<\/code><\/pre>\n<p>You also need to install the Ionic Native package for each plugin you want to add. Please see the Ionic Native documentation for complete instructions on how to add and use the plugins.<\/p>\n<p>To use a plugin, import and add the plugin provider to your @NgModule, and then inject it where you wish to use it.<\/p>\n<pre><code class=\"ts\">\/\/ app.module.ts\nimport { Camera } from &#039;@ionic-native\/camera&#039;;\nimport { CameraMock } from &#039;@ionic-native-mocks\/camera&#039;;\n...\n\n@NgModule({\n  ...\n\n  providers: [\n    ...\n    { provide: Camera, useClass: CameraMock }\n  ]\n  ...\n})\nexport class AppModule { }\n\n\/\/ elsewhere in your app\nimport { Platform } from &#039;ionic-angular&#039;;\nimport { Camera, CameraOptions } from &#039;@ionic-native\/camera&#039;;\n\n\n@Component({ ... })\nexport class MyComponent {\n\n  constructor(private camera: Camera, private platform: Platform) {\n\n    platform.ready().then(() =&gt; {\n\n    const options: CameraOptions = {\n        quality: 100,\n        destinationType: this.camera.DestinationType.DATA_URL,\n        encodingType: this.camera.EncodingType.JPEG,\n        mediaType: this.camera.MediaType.PICTURE\n    }\n\n      this.camera.getPicture(options).then((imageData) =&gt; {\n        \/\/ imageData is either a base64 encoded string or a file URI\n        \/\/ If it&#039;s base64:\n        console.log(imageData);\n        let base64Image = &#039;data:image\/jpeg;base64,&#039; + imageData;\n    }, (err) =&gt; {\n        \/\/ Handle error\n    });\n    });\n  }\n}\n<\/code><\/pre>\n<p>By design, the Ionic Native Mocks I wrote are very generic. They return the bare minimum amount of data for them to function. For them to be more useful in your project, you may want to customize them. For example, for the bar code scanner, I wanted the mock to always return a valid product code.<\/p>\n<p>To begin modifying an Ionic Native Mock file, you will first need to get the code directly from GitHub and the source <a href=\"https:\/\/github.com\/chrisgriffith\/ionic-native-mocks\/tree\/master\/src\/@ionic-native-mocks\/plugins\/barcode-scanner\">Typescript code<\/a> and add it to your project manually. While each plugin is available via npm, those files are installed in your project\u2019s \u201cnode_modules\u201d folder and can easily get overwritten or deleted.<\/p>\n<p>In your project, create a new directory named mocks, and create another directory named barcodescanner. Within that directory, download the index.ts file from Github into this directory.<\/p>\n<p>Now let\u2019s adjust out app.module.ts file. Like all Ionic Native modules, we need to import it.<\/p>\n<pre><code class=\"ts\">import { BarcodeScanner } from &#039;@ionic-native\/barcode-scanner&#039;;\n<\/code><\/pre>\n<p>Also import our plugin mock as well.<\/p>\n<pre><code class=\"ts\">import { BarcodeScannerMock } from &#039;..\/mocks\/barcodescanner&#039;;\n<\/code><\/pre>\n<p>Instead of including the Ionic Native plugin directly into the providers array, we instead tell Angular to provide a mapping to our mock. This allows us to keep the rest of application referencing the real Ionic Native module, yet use the code from the mock instead.<\/p>\n<pre><code class=\"ts\">{ provide: BarcodeScanner, useClass: BarcodeScannerMock }\n<\/code><\/pre>\n<p>At this point we could build our app, making calls to the barcode scanner plugin without needing to test on an actual device. But, out of the box, the barcode scanner mock is going to return an empty string.<\/p>\n<p>But, let\u2019s have it return something that we might want our user to scan. For my original app, it was a QR code on our packaging. Open the index.ts file within our project and change the scan function to<\/p>\n<pre><code class=\"ts\">scan(options?: BarcodeScannerOptions): Promise {\n  let code=&#039;NCC-1701&#039;;\n  let theResult:BarcodeScanResult= {format:&#039;QR_CODE&#039;, cancelled:false, text:code };\n\n  return new Promise((resolve, reject) =&gt; {\n    resolve(theResult);\n  });\n}\n<\/code><\/pre>\n<p>Save the file, and run the application. Now when you call the barcode scanner, it will return your custom data. When you are ready to use the real plugin, change the provider and remove the import of the mock.<\/p>\n<h2>Parting words<\/h2>\n<p>Hopefully, this post has shown you how to leverage <a href=\"https:\/\/github.com\/chrisgriffith\/ionic-native-mocks\">Ionic Native Mocks<\/a> into your Ionic application, and how it can reduce the friction during the build &amp; test cycle of development. The mocks are are open source, and if you find an issue, please let me know. Happy Coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a guest post from Chris Griffith. Chris is UI\/UX engineer, an educator in the Ionic community and author of the Ionic Native Mocks library. When you create an Ionic application, often you have need to include a Cordova plugin or two. In fact, several Cordova plugins are included when you generate an Ionic [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"publish_to_discourse":"","publish_post_category":"","wpdc_auto_publish_overridden":"","wpdc_topic_tags":"","wpdc_pin_topic":"","wpdc_pin_until":"","discourse_post_id":"","discourse_permalink":"","wpdc_publishing_response":"","wpdc_publishing_error":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2195","post","type-post","status-publish","format-standard","hentry","category-all"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v23.0 (Yoast SEO v23.0) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Ionic Native Mocks - Ionic Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/ionic.io\/blog\/ionic-native-mocks\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Ionic Native Mocks\" \/>\n<meta property=\"og:description\" content=\"This is a guest post from Chris Griffith. Chris is UI\/UX engineer, an educator in the Ionic community and author of the Ionic Native Mocks library. When you create an Ionic application, often you have need to include a Cordova plugin or two. In fact, several Cordova plugins are included when you generate an Ionic [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/ionic.io\/blog\/ionic-native-mocks\" \/>\n<meta property=\"og:site_name\" content=\"Ionic Blog\" \/>\n<meta property=\"article:published_time\" content=\"2018-05-09T15:06:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-05-09T15:08:39+00:00\" \/>\n<meta name=\"author\" content=\"Mike Hartington\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@mhartington\" \/>\n<meta name=\"twitter:site\" content=\"@ionicframework\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mike Hartington\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks#article\",\"isPartOf\":{\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks\"},\"author\":{\"name\":\"Mike Hartington\",\"@id\":\"https:\/\/ionic.io\/blog\/#\/schema\/person\/c8c92b04d526adb925ea514c619a267b\"},\"headline\":\"Ionic Native Mocks\",\"datePublished\":\"2018-05-09T15:06:42+00:00\",\"dateModified\":\"2018-05-09T15:08:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks\"},\"wordCount\":929,\"commentCount\":6,\"publisher\":{\"@id\":\"https:\/\/ionic.io\/blog\/#organization\"},\"articleSection\":[\"All\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/ionic.io\/blog\/ionic-native-mocks#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks\",\"url\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks\",\"name\":\"Ionic Native Mocks - Ionic Blog\",\"isPartOf\":{\"@id\":\"https:\/\/ionic.io\/blog\/#website\"},\"datePublished\":\"2018-05-09T15:06:42+00:00\",\"dateModified\":\"2018-05-09T15:08:39+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/ionic.io\/blog\/ionic-native-mocks\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/ionic.io\/blog\/ionic-native-mocks#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/ionic.io\/blog\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Ionic Native Mocks\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/ionic.io\/blog\/#website\",\"url\":\"https:\/\/ionic.io\/blog\/\",\"name\":\"ionic.io\/blog\",\"description\":\"Build amazing native and progressive web apps with the web\",\"publisher\":{\"@id\":\"https:\/\/ionic.io\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/ionic.io\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/ionic.io\/blog\/#organization\",\"name\":\"Ionic\",\"url\":\"https:\/\/ionic.io\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/ionic.io\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2020\/10\/white-on-color.png\",\"contentUrl\":\"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2020\/10\/white-on-color.png\",\"width\":1920,\"height\":854,\"caption\":\"Ionic\"},\"image\":{\"@id\":\"https:\/\/ionic.io\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/ionicframework\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/ionic.io\/blog\/#\/schema\/person\/c8c92b04d526adb925ea514c619a267b\",\"name\":\"Mike Hartington\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/ionic.io\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2018\/08\/mike-headshot-2-smaller-150x150.png\",\"contentUrl\":\"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2018\/08\/mike-headshot-2-smaller-150x150.png\",\"caption\":\"Mike Hartington\"},\"description\":\"Director of Developer Relations\",\"sameAs\":[\"https:\/\/twitter.com\/mhartington\",\"https:\/\/x.com\/mhartington\"],\"url\":\"https:\/\/ionic.io\/blog\/author\/mike\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Ionic Native Mocks - Ionic Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/ionic.io\/blog\/ionic-native-mocks","og_locale":"en_US","og_type":"article","og_title":"Ionic Native Mocks","og_description":"This is a guest post from Chris Griffith. Chris is UI\/UX engineer, an educator in the Ionic community and author of the Ionic Native Mocks library. When you create an Ionic application, often you have need to include a Cordova plugin or two. In fact, several Cordova plugins are included when you generate an Ionic [&hellip;]","og_url":"https:\/\/ionic.io\/blog\/ionic-native-mocks","og_site_name":"Ionic Blog","article_published_time":"2018-05-09T15:06:42+00:00","article_modified_time":"2018-05-09T15:08:39+00:00","author":"Mike Hartington","twitter_card":"summary_large_image","twitter_creator":"@mhartington","twitter_site":"@ionicframework","twitter_misc":{"Written by":"Mike Hartington","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks#article","isPartOf":{"@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks"},"author":{"name":"Mike Hartington","@id":"https:\/\/ionic.io\/blog\/#\/schema\/person\/c8c92b04d526adb925ea514c619a267b"},"headline":"Ionic Native Mocks","datePublished":"2018-05-09T15:06:42+00:00","dateModified":"2018-05-09T15:08:39+00:00","mainEntityOfPage":{"@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks"},"wordCount":929,"commentCount":6,"publisher":{"@id":"https:\/\/ionic.io\/blog\/#organization"},"articleSection":["All"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/ionic.io\/blog\/ionic-native-mocks#respond"]}]},{"@type":"WebPage","@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks","url":"https:\/\/ionic.io\/blog\/ionic-native-mocks","name":"Ionic Native Mocks - Ionic Blog","isPartOf":{"@id":"https:\/\/ionic.io\/blog\/#website"},"datePublished":"2018-05-09T15:06:42+00:00","dateModified":"2018-05-09T15:08:39+00:00","breadcrumb":{"@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/ionic.io\/blog\/ionic-native-mocks"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/ionic.io\/blog\/ionic-native-mocks#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/ionic.io\/blog"},{"@type":"ListItem","position":2,"name":"Ionic Native Mocks"}]},{"@type":"WebSite","@id":"https:\/\/ionic.io\/blog\/#website","url":"https:\/\/ionic.io\/blog\/","name":"ionic.io\/blog","description":"Build amazing native and progressive web apps with the web","publisher":{"@id":"https:\/\/ionic.io\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ionic.io\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/ionic.io\/blog\/#organization","name":"Ionic","url":"https:\/\/ionic.io\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ionic.io\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2020\/10\/white-on-color.png","contentUrl":"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2020\/10\/white-on-color.png","width":1920,"height":854,"caption":"Ionic"},"image":{"@id":"https:\/\/ionic.io\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/ionicframework"]},{"@type":"Person","@id":"https:\/\/ionic.io\/blog\/#\/schema\/person\/c8c92b04d526adb925ea514c619a267b","name":"Mike Hartington","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ionic.io\/blog\/#\/schema\/person\/image\/","url":"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2018\/08\/mike-headshot-2-smaller-150x150.png","contentUrl":"https:\/\/ionic.io\/blog\/wp-content\/uploads\/2018\/08\/mike-headshot-2-smaller-150x150.png","caption":"Mike Hartington"},"description":"Director of Developer Relations","sameAs":["https:\/\/twitter.com\/mhartington","https:\/\/x.com\/mhartington"],"url":"https:\/\/ionic.io\/blog\/author\/mike"}]}},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/posts\/2195","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/comments?post=2195"}],"version-history":[{"count":0,"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/posts\/2195\/revisions"}],"wp:attachment":[{"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/media?parent=2195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/categories?post=2195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ionic.io\/blog\/wp-json\/wp\/v2\/tags?post=2195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}