Back to Blog Home
← all posts

Unit testing with NativeScript 8.0

May 11, 2021 — by Technical Steering Committee (TSC)

The ability to unit test your iOS and Android apps is critical for any team. Let's look at how to unit test with NativeScript 8.0.

1. NativeScript CLI >= 8.0.2

You will need the latest NativeScript CLI 8.0.2 or higher:

npm install -g nativescript

You can then confirm you have the latest using ns -v

2. Add the unit test runner

You can add the unit test runner to any app with:

ns test init

You will be prompted for the unit test framework to use:

? Select testing framework: › - Use arrow-keys. Return to submit.
❯   jasmine
    mocha
    qunit

This will install several unit test dependencies in addition to adding a tests folder to your app with the following tests/example.ts spec (ie, using jasmine as an example):

// A sample Jasmine test
describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});

3. Run your unit tests

iOS

ns test ios
ios unit test runner

Android

ns test android
android unit test runner

Test your app!

Now that we have unit testing setup we can test all sorts of aspects of our app. For example let's start out be creating an iOS and Android specific unit test.

Create tests/device.android.ts with the following:

import { Device } from "@nativescript/core";

describe("Android Device", function() {
  it("should use > 23 SDK", function() {
    expect(parseFloat(Device.sdkVersion) > 23).toBeTrue();
  });
});

When we test now with: ns test android, we will see:

ios unit test runner

Similarly let's create tests/device.ios.ts with the following:

import { Device } from "@nativescript/core";

describe("iOS Device", function() {
  it("should use > 14 SDK", function() {
    expect(Device.sdkVersion).toBe('12');
  });
});

When we test now with: ns test ios, we will see:

ios unit test runner

Wait! That's a failure!

Yep, definitely a failed test. Let's fix it with the following:

import { Device } from "@nativescript/core";

describe("iOS Device", function() {
  it("should use > 14 SDK", function() {
    expect(parseFloat(Device.sdkVersion) > 14).toBeTrue();
  });
});

When we test now with: ns test ios, we will see:

ios unit test runner

Recap of versions you will want if upgrading

If you have unit testing in your app already and just updating dependencies make sure you have the latest CLI as mentioned and the following in your devDependencies:

"devDependencies": {
  ...,
  "@nativescript/unit-test-runner": "~2.0.0",
  "@nativescript/webpack": "beta",
  ...
}

Summary

Unit testing NativeScript apps for iOS and Android is efficient as well as easy to use. We hope this helps you provide some coverage over critical paths in your app.

You can also try this with the different "flavors" of NativeScript and there will be a subsequent blog post soon detailing a few extra's with specific flavors.