Thursday, 7 November 2019

How do I mock API requests in Nativescript?

I'm using Nativescript 8.x with Angular 8.x and I'm doing my End to End tests with Appium + Mocha + Chai. I would like to mock an API calls I do over nativescript-http but I cannot get this working correctly.

Here is the code I'm trying to mock

login() {
    console.log("Login called")

    this.http.get("https://example.com/resource")
        .pipe(
            map(res =>{
                console.log(res);
            })
        )
        .subscribe(res => {
            this.router.navigate(["/home"]);
        });

}

I've tried to use 'nock'

import { AppiumDriver, createDriver, SearchOptions, nsCapabilities } from "nativescript-dev-appium";
import { assert } from "chai";
import * as nock from "nock";

const addContext = require('mochawesome/addContext');

describe("Login Screens", () => {
    let driver: AppiumDriver;

    before(async function(){
        nsCapabilities.testReporter.context = this; 
        driver = await createDriver(); // wait for the driver instance to be created
    });

    after(async function () {
        await driver.quit();    //  destroy the driver instance
        console.log("Quit driver!");
    });

    it.only("should login", async function () {

        nock('http://www.example.com')
            .get('/resource')
            .reply(200, 'path matched')

        // Login
        const btnLoginTap = await driver.findElementByAccessibilityId("btnLogin");
        await btnLoginTap.click();

        // Check heading
        const lblHeadingHome = await driver.findElementByAccessibilityId("headingHome");
        assert.equal(await lblHeadingHome.text(), "Home");

        nock.cleanAll();
    });

When I run my end to end tests with;

npm run e2e -- --runType device.samsung

I get the error;

> @ e2e /home/map7/code/asset_management
> node ./node_modules/nativescript-dev-appium/check-dev-deps.js &&  tsc -p e2e  &&  mocha --opts ./e2e/config/mocha.opts  "--runType" "device.samsung"

Parsed args:   {"port":4723,"projectDir":"/home/map7/code/asset_management","projectBinary":"/home/map7/code/asset_management/node_modules/.bin","pluginRoot":"/home/map7/code/asset_management/node_modules/nativescript-dev-appium","pluginBinary":"/home/map7/code/asset_management/node_modules/nativescript-dev-appium/node_modules/.bin","wdaLocalPort":8410,"testFolder":"e2e","runType":"device.samsung","appiumCapsLocation":"/home/map7/code/asset_management/e2e/config/appium.capabilities.json","verbose":false,"cleanApp":false,"path":"/home/map7/code/asset_management","capabilitiesName":"appium.capabilities.json","driverConfig":{"host":"localhost","port":4723},"logImageTypes":[]}


/home/map7/code/asset_management/e2e/config/appium.capabilities.json
Capabilities found at: /home/map7/code/asset_management/e2e/config/appium.capabilities.json 
Automation name set to: UIAutomator2 
To change automation name, you need to set it in appium capabilities!
Available applications:  ["platforms/android/app/build/outputs/apk/debug/app-debug.apk"]
Pick first application:   "platforms/android/app/build/outputs/apk/debug/app-debug.apk"
Application full path: /home/map7/code/asset_management/platforms/android/app/build/outputs/apk/debug/app-debug.apk 
Default device:  { name: 'samsung_galaxy_s8',
  apiLevel: '24',
  releaseVersion: '7.0',
  platform: 'android',
  type: 'emulator',
  status: 'booted',
  token: '5546' }
Trying to resolve automatically appPackage!
Setting capabilities device.samsung{ "appPackage" : "org.nativescript.NativeScriptTemplate2" }!
Trying to resolve automatically appActivity!
Setting capabilities device.samsung{ "appActivity : "com.tns.NativeScriptActivity" }!
Setting application name as NativeScriptTemplate2
Check and uninstall application from device. 
Application: org.nativescript.NativeScriptTemplate2 is not installed!
Server args:   ["-p","4723","--log-level","info"]
** Message: Unable to use GNOME Shell's builtin screenshot interface, resorting to fallback X11.
  Login Screens
Session info:  
{ platform: 'LINUX',
  webStorageEnabled: false,
  takesScreenshot: true,
  javascriptEnabled: true,
  databaseEnabled: false,
  networkConnectionEnabled: true,
  locationContextEnabled: false,
  warnings: {},
  desired:
   { platformName: 'android',
     platformVersion: '24',
     deviceName: 'samsung_galaxy_s8',
     avd: 'samsung_galaxy_s8',
     lt: 60000,
     newCommandTimeout: 720,
     noReset: false,
     fullReset: false,
     app:
      '/home/map7/code/asset_management/platforms/android/app/build/outputs/apk/debug/app-debug.apk',
     automationName: 'UIAutomator2',
     udid: 'emulator-5546',
     appPackage: 'org.nativescript.NativeScriptTemplate2',
     appActivity: 'com.tns.NativeScriptActivity' },
  platformName: 'android',
  platformVersion: '7.0',
  deviceName: 'emulator-5546',
  avd: 'samsung_galaxy_s8',
  lt: 60000,
  newCommandTimeout: 720,
  noReset: false,
  fullReset: false,
  app:
   '/home/map7/code/asset_management/platforms/android/app/build/outputs/apk/debug/app-debug.apk',
  automationName: 'UIAutomator2',
  udid: 'emulator-5546',
  appPackage: 'org.nativescript.NativeScriptTemplate2',
  appActivity: 'com.tns.NativeScriptActivity',
  deviceUDID: 'emulator-5546',
  deviceApiLevel: 24,
  deviceScreenSize: '480x854',
  deviceScreenDensity: 160,
  deviceModel: 'Android SDK built for x86',
  deviceManufacturer: 'Google',
  pixelRatio: 1,
  statBarHeight: 24,
  viewportRect: { left: 0, top: 24, width: 480, height: 830 } }
Appium settings:  
{ imageMatchThreshold: 0.4,
  fixImageFindScreenshotDims: true,
  fixImageTemplateSize: false,
  fixImageTemplateScale: false,
  defaultImageTemplateScale: 1,
  checkForImageElementStaleness: true,
  autoUpdateImageElementPosition: false,
  imageElementTapStrategy: 'w3cActions',
  getMatchedImageResult: false,
  ignoreUnimportantViews: false,
  allowInvisibleElements: false,
  actionAcknowledgmentTimeout: 3000,
  elementResponseAttributes: '',
  enableMultiWindows: false,
  enableNotificationListener: true,
  keyInjectionDelay: 0,
  scrollAcknowledgmentTimeout: 200,
  shouldUseCompactResponses: true,
  waitForIdleTimeout: 10000,
  waitForSelectorTimeout: 10000,
  normalizeTagNames: false,
  shutdownOnPowerDisconnect: true,
  trackScrollEvents: true,
  wakeLockTimeout: 86395751 }
Appium driver has started successfully!
** Message: Unable to use GNOME Shell's builtin screenshot interface, resorting to fallback X11.
Actual view port: {"timeOutSeconds":2,"tolerance":0,"toleranceType":"pixel","waitBeforeCreatingInitialImageCapture":5000,"donNotAppendActualSuffixOnIntialImageCapture":false,"keepOriginalImageSize":true,"keepOriginalImageName":false,"isDeviceSpecific":true,"cropRectangle":{"x":0,"y":24,"width":480,"height":830},"overwriteActualImage":false}
    1) should login
Killing driver...
Driver is dead!
** Message: Unable to use GNOME Shell's builtin screenshot interface, resorting to fallback X11.
Quit driver!

Shut down!!!
** Message: Unable to use GNOME Shell's builtin screenshot interface, resorting to fallback X11.
About to exit with code: exit
org.nativescript.NativeScriptTemplate2 successfully uninstalled.
Application from device is uninstalled. 
Application: org.nativescript.NativeScriptTemplate2 is not installed!
Application from device is uninstalled. 
Exited from appium

  0 passing (25s)
  1 failing

  1) Login Screens
       should login:
     Error: [waitForElementByAccessibilityId("headingHome",5000)] Element condition wasn't satisfied!
      at /home/map7/code/asset_management/node_modules/wd/lib/commands.js:979:12
      at /home/map7/code/asset_management/node_modules/wd/lib/commands.js:884:11
      at /home/map7/code/asset_management/node_modules/wd/lib/commands.js:966:13
      at /home/map7/code/asset_management/node_modules/wd/node_modules/async/dist/async.js:3888:9
      at /home/map7/code/asset_management/node_modules/wd/node_modules/async/dist/async.js:473:16
      at replenish (node_modules/wd/node_modules/async/dist/async.js:1006:25)
      at /home/map7/code/asset_management/node_modules/wd/node_modules/async/dist/async.js:1016:9
      at eachOfLimit (node_modules/wd/node_modules/async/dist/async.js:1041:24)
      at /home/map7/code/asset_management/node_modules/wd/node_modules/async/dist/async.js:1046:16
      at _parallel (node_modules/wd/node_modules/async/dist/async.js:3879:5)
      at Object.series (node_modules/wd/node_modules/async/dist/async.js:4735:5)
      at /home/map7/code/asset_management/node_modules/wd/lib/commands.js:964:15
      at /home/map7/code/asset_management/node_modules/wd/lib/promise-webdriver.js:52:11
      at _fulfilled (node_modules/q/q.js:854:54)
      at /home/map7/code/asset_management/node_modules/q/q.js:883:30
      at Promise.promise.promiseDispatch (node_modules/q/q.js:816:13)
      at /home/map7/code/asset_management/node_modules/q/q.js:624:44
      at runSingle (node_modules/q/q.js:137:13)
      at flush (node_modules/q/q.js:125:13)
      at process._tickCallback (internal/process/next_tick.js:61:11)



npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ e2e: `node ./node_modules/nativescript-dev-appium/check-dev-deps.js &&  tsc -p e2e  &&  mocha --opts ./e2e/config/mocha.opts  "--runType" "device.samsung"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/map7/.npm/_logs/2019-10-30T02_35_55_863Z-debug.log

This is because the mock didn't work at all.



from How do I mock API requests in Nativescript?

No comments:

Post a Comment