A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.nativescript.org/guide/testing below:

Unit Testing | NativeScript

Regularly writing and executing unit tests using tools like Jasmine, Mocha with Chai, or QUnit through the NativeScript CLI helps ensure proper functioning of new features and prevents regressions in existing functionality during app development.

To run your unit tests, the NativeScript CLI uses Karma.

Before You Begin

Before writing and running unit tests, the completion of the following steps must be verified.

  1. Install and configure the NativeScript CLI on your system.

  2. If you don't have any projects, create a new project and navigate to the directory of the newly created directory.

    bash
    ns create projectName
    cd projectName
  3. If you want to create tests for an existing directory, navigate to the directory of the project.

    bash
    cd existingProjectDirectory

Note

You don't need to explicitly add the platforms for which you want to test your project. The NativeScript CLI will configure your project when you begin to run your tests.

Configure Your Project

The NativeScript CLI lets you choose between three widely popular unit testing frameworks: Jasmine, Mocha with Chai and QUnit. You need to configure the project for unit testing by choosing a framework. You can use only one framework at a time.

To initialize your project for unit testing, run the following command and, when prompted, use the keyboard arrows to select the framework that you want to use.

This operation applies the following changes to your project.

Note

To enable and write unit tests for TypeScript or Angular project install the TypeScript typings for the selected testing framework.

bash
npm i @types/jasmine --save-dev
bash
npm i @types/mocha --save-dev
bash
npm i @types/qunit --save-dev
Write Your Tests

With the NativeScript CLI, you can extensively test all JavaScript-related functionality. You cannot test styling and UI which are not applied or created via JavaScript.

When creating tests for a new or existing functionality, keep in mind the following specifics.

When creating tests for a new or existing functionality, keep in mind the following limitations.

The following samples test the initial value of the counter and the message in the Hello World template. These tests show the specifics and limitations outlined above.

js
var mainViewModel = require('../main-view-model') //Require the main view model to expose the functionality inside it.

describe('Hello World Sample Test:', function () {
  it('Check counter.', function () {
    expect(mainViewModel.createViewModel().counter).toEqual(42) //Check if the counter equals 42.
  })
  it('Check message.', function () {
    expect(mainViewModel.createViewModel().message).toBe('42 taps left') //Check if the message is "42 taps left".
  })
})
js
// (Angular w/TypeScript)
// As our intention is to test an Angular component that contains annotations
// we need to include the reflect-metadata dependency.
import 'reflect-metadata'

// A sample Jasmine test
describe('A suite', function () {
  it('contains spec with an expectation', function () {
    expect(true).toBe(true)
  })
})
js
var mainViewModel = require('../main-view-model') //Require the main view model to expose the functionality inside it.

describe('Hello World Sample Test:', function () {
  it('Counter should be 42 on start.', function () {
    assert.equal(mainViewModel.createViewModel().counter, 42) //Assert that the counter equals 42.
  })
  it('Message should be "42 taps left" on start.', function () {
    assert.equal(mainViewModel.createViewModel().message, '42 taps left') //Assert that the message is "42 taps left".
  })
})
js
var mainViewModel = require('../main-view-model') //Require the main view model to expose the functionality inside it.

QUnit.test('Hello World Sample Test:', function (assert) {
  assert.equal(
    mainViewModel.createViewModel().counter,
    42,
    'Counter, 42; equal succeeds.',
  ) //Assert that the counter equals 42.
  assert.equal(
    mainViewModel.createViewModel().message,
    '42 taps left',
    'Message, 42 taps left; equal succeeds.',
  ) //Assert that the message is "42 taps left".
})
Angular TestBed Integration

To use TestBed you have to alter your karma.conf.js to:

js
// list of files / patterns to load in the browser
    files: [
      'src/tests/setup.ts',
      'src/tests/**/*.spec.ts'
    ],

The file src/tests/setup.ts should look like this for jasmine:

js
import 'nativescript-angular/zone-js/testing.jasmine'
import { nsTestBedInit } from 'nativescript-angular/testing'
nsTestBedInit()

or if using mocha:

js
import 'nativescript-angular/zone-js/testing.mocha'
import { nsTestBedInit } from 'nativescript-angular/testing'
nsTestBedInit()

Then you can use it within the spec files, e.g. example.spec.ts:

js
import { Component, ElementRef, NgZone, Renderer2 } from '@angular/core';
import { ComponentFixture, async } from '@angular/core/testing';
import { StackLayout } from '@nativescript/core';
import {
    nsTestBedAfterEach,
    nsTestBedBeforeEach,
    nsTestBedRender
} from 'nativescript-angular/testing';

@Component({
    template: `
        <StackLayout><Label text="Layout"></Label></StackLayout>
    `
})
export class ZonedRenderer {
    constructor(public elementRef: ElementRef, public renderer: Renderer2) {}
}

describe('Renderer E2E', () => {
    beforeEach(nsTestBedBeforeEach([ZonedRenderer]));
    afterEach(nsTestBedAfterEach(false));
    afterAll(() => {});

    it('executes events inside NgZone when listen is called outside NgZone', async(() => {
        const eventName = 'someEvent';
        const view = new StackLayout();
        const eventArg = { eventName, object: view };
        const callback = arg => {
            expect(arg).toEqual(eventArg);
            expect(NgZone.isInAngularZone()).toBeTruthy();
        };
        nsTestBedRender(ZonedRenderer).then(
            (fixture: ComponentFixture<ZonedRenderer>) => {
                fixture.ngZone.runOutsideAngular(() => {
                    fixture.componentInstance.renderer.listen(
                        view,
                        eventName,
                        callback
                    );

                    view.notify(eventArg);
                });
            }
        );
    }));
});
Run Your Tests

After you have completed your test suite, you can run it on physical devices or in the native emulators.

Requirements

Before running your tests, verify that your development machine and your testing devices meet the following prerequisites.

Run the Tests

To execute your test suite on any connected Android devices or running Android emulators, run the following command.

Note

Be sure you have prepared the app at least once before starting the unit test runner.

To execute your test suite on connected iOS devices, run the following command.

To execute your test suite in the iOS Simulator, run the following command.

bash
ns test ios --emulator

To execute your test suite in CI make sure to add --justlaunch. This parameter will exit the simulator.

bash
ns test ios --emulator --justlaunch

Each execution of ns test consists of the following steps, performed automatically.

  1. The CLI starts a Karma server on the development machine.
  2. The CLI prepares, builds and deploys your project, if not already deployed. If already deployed, the CLI synchronizes changes to the application package.
  3. The CLI embeds the NativeScript unit test runner and your host network and Karma configuration in the deployed package.
  4. The CLI launches the main module of the NativeScript unit test runner instead of launching the main module of your app.
  5. The NativeScript unit test runner uses the embedded network configuration to try to connect to the Karma server on the development machine.
  6. When the connection between the NativeScript unit test runner and the Karma server is established, the test runner begins the execution of the unit tests.
  7. When the execution completes, the NativeScript unit test runner reports the results to the Karma server.
  8. The Karma server reports the results on the command line.
Re-Run Tests on Code Change

The NativeScript can continuously monitor your code for changes and when such changes occur, it can deploy those changes to your testing devices and re-run your tests.

To enable this behavior, run your ns test command with the --watch flag. For example:

bash
ns test android --watch
ns test ios --watch
ns test ios --emulator --watch

The NativeScript CLI remains active and re-runs tests on code change. To unlock the console, press Ctrl+C to stop the process.

Configure the Karma Server

When you configure your project for unit testing, the NativeScript CLI adds karma.conf.js to the root of your project. This file contains the default configuration of the Karma server, including default port and selected testing framework. You can edit this file to customize your Karma server.

When you modify karma.conf.js, make sure that your changes meet the specification of the Karma Configuration File.

Continuous Integration

To integrate the NativeScript unit test runner into a continuous integration process, you need to configure a Karma reporter, for example, the JUnit reporter.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4