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.
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
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);
});
});
ns test ios
ns test android
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:
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:
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:
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",
...
}
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.