jeudi 2 janvier 2020

Testcafe takes about 2 minutes everytime to trigger the browser. What could be the fix here?

I have node 12.14.0, npm 6.13.4 and testcafe 1.7.1 in my Windows 10 PC.

I am trying to run a basic sample script using the command testcafe chrome test1.js:

import { Selector } from 'testcafe';

fixture `Getting Started`
    .page `http://devexpress.github.io/testcafe/example`;

test('My first test', async t => {
    // Test code
});

It takes about 2 minutes everytime for the browser to be triggered. The test runs fine after that though.

What could be causing this delay? I also tried running it through npm command and got the same result.

How can I get more verbose debugging information from hammerhead?

I am running into an issue where my web code is invoking an ajax call to another endpoint on the same server that is not completing. I can see in the server logs that the request is processed and the response is sent, but the network tool shows the response as not finished (stalled) even after several minutes.

I am looking for more details on what is happening in the proxy (perhaps it is waiting on more data from the server, etc). But I cannot find any logging from the proxy to assist in debugging.

EDIT: I have noticed this happens on all proxy requests with isXhr set.

mercredi 1 janvier 2020

Using the wiremock Mappings in the spring boot application to mimic the external api behavious

I have a use case where I need to test the external apis request for my application.

I have figured out the mappings part using the wiremock --proxy all and record mappings option but I am not able to use those wiremock mappings for my testing. I need to know a way where I can host those mappings/files on a separate port and use them for request response. Thanks

Flutter UnitTest: Two different mocks for the same class

currently I am writing Unit tests for my mobile web application (Android app). The unit tests refer to my login system built upon Google Firebase Auth.

With one of the latest releases of the firebase authentication plugins, the return type of some functions have been changed. For example, the method firebaseAuth.signInWithEmailAndPassword has been changed from FirebaseUser to AuthResult

I have a login function in a AuthService.dart with the following content:

Future<bool> login(LoginUserData userData) async {
    try {
      _checkUserDataValidity(userData);
      final AuthResult authResult= await firebaseAuth.signInWithEmailAndPassword(email: userData.email, password: userData.password);
      return authResult.user != null;
    } catch (exception) {
      return false;
    }
  }

So, as you can see I am only checking whether the data of the user is correct or not - I am returning a boolean to check this in another file (if true is returned, the Navigator routes to another site, if wrong is returned an error message pops up).

My Unit tests for example checks for a few cases:

  1. Correct data
  2. Incorrect data (userData is not empty or null)
  3. Empty data

Example code of a test:

test('Login should work with valid user data', () async {
      when(
        firebaseAuthMock.signInWithEmailAndPassword(
          email: testValidUserData.email,
          password: testValidUserData.password,
        )
      ).thenAnswer(
        (_) => Future<AuthResultMock>.value(firebaseAuthResultMock)
      );

      final bool actionSuccess = await authService.login(testValidUserData);

      verify(
        firebaseAuthMock.signInWithEmailAndPassword(
          email: testValidUserData.email,
          password: testValidUserData.password,
        )
      ).called(1);

      expect(actionSuccess, true);
    });

To cover case one and two of my list above, I'd like to use two different Mocks. One Mock to contain a user, the other mock has no user in it.

Current issue:

(_) => Future<AuthResultMock>.value(firebaseAuthResultMock)

in my test is in conflict with this code from the AuthServie.dart

return authResult.user != null;

The mock is having null as user. How can I change this? :) Bt.w I am using Mockito.

My idea was:

  1. For correct data, to return a mock, that contains a user.
  2. For invalid data, to return a mock, that has null as user.

Thank you so much. :)

Rspec testing strong params in Rails not working (wrong number of arguments)

I'm trying to implement some testing for my controller strong params and following the docs to the 'T'.

My controller:

class FutureOutagesController < ApplicationController
  before_action :find_future_outage, only: [:show, :update, :destroy] 
  before_action :future_outage_params, only: [:create, :update, :destroy]

  def index 
    @future_outages = FutureOutage.all
  end

  def show
  end

  def create
    @future_outage = FutureOutage.new(future_outage_params)
  end

  def update
  end

  def destroy
  end

  private 

  def find_future_outage 
    @future_outage = FutureOutage.find(params[:id])
  end 

  def future_outage_params
    params.require(:future_outage).permit(:start_time, :end_time, :reason, :service_id)
  end
end

my rsepc test with FactoryBot and ShouldaMatchers:

require 'rails_helper'

RSpec.describe FutureOutagesController, type: :controller do
    let(:fo) { build :future_outage }

  context 'test params' do
    it do
      params = {
        future_outage: {
          start_time: fo.start_time,
          end_time: fo.end_time,
          reason: fo.reason,
          service_id: fo.service_id
        }
      } 
      should permit(:start_time, :end_time, :reason, :service_id).
      for(:create, params: params).on(:future_outage)
    end
  end

end

I get the error:

Failures:

  1) FutureOutagesController test params is expected to (for POST #create) restrict parameters on :future_outage to :start_time, :end_time, :reason, and :service_id
     Failure/Error:
       should permit(:start_time, :end_time, :reason, :service_id).
       for(:create, params: params).on(:future_outage)

     ActionView::Template::Error:
       wrong number of arguments (given 2, expected 1)
     # ./spec/controllers/future_outages_controller_spec.rb:25:in `block (3 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # ArgumentError:
     #   wrong number of arguments (given 2, expected 1)
     #   ./spec/controllers/future_outages_controller_spec.rb:25:in `block (3 levels) in <top (required)>'

What am I doing wrong?

Angular test case Failing using command npm test Angular project

Please help me to resolve my issues with my Angular project. As It is giving me errors in my spec file while run with npm test.

Sharing my whole source code and errors what I am getting.

navbar.component.html

<div class="app-navbar">
  <ul>
    <li class="nav-item" *ngFor="let navItem of subsections" [class.active-subsection]="currentSubSection===navItem">
      <a href="javascript:void(0);" (click)="dispatchAction(navItem)"> </a>
    </li>
  </ul>
</div>

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';

import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { News } from '../../model/news';

// ngrx store 
import { AppState } from '../../store/reducers';
import { getNewsSection } from '../../store/selectors/news.selectors';
import * as fromActions from '../../store/actions';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})

export class NavbarComponent implements OnInit {
  sectionNews: News[];
  currentSubSection: string;
  subsections: string[] = [];
  unsubscribe: Subject<void> = new Subject();

  constructor(private store: Store<AppState>) { }

  ngOnInit() {
    this.initSubscriptions();
  }

  /**
   * Holding Subscriptions
   */
  initSubscriptions(): void {

    // subscription to store & selector to pull all section news
    this.store.pipe(select(getNewsSection))
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        sectionNews => {
          this.currentSubSection = '';
          this.subsections = [];
          for (const item of sectionNews) {
            //pulling all subsection which is unique and non empty
            if (item.subsection.length && !this.subsections.includes(item.subsection)) {
              this.subsections.push(item.subsection);
            }
          }
        }
      );
}
  /**
   * Filter news by dispatching subsection filter action
   * @param filter - subsection string
   */
  dispatchAction(filter: string): void {
    this.currentSubSection = filter;
    this.store.dispatch(new fromActions.FilterSubSection(filter));
  }

}

navbar.component.spec.ts

it('should display subsection in template', async() => {
    // assign mock values to subsections array
    component.subsections = ['movie', 'tech', 'money'];
    // <a> tag in html will contain one of values of subsections array. select the <a> tag using query(By.css())
    const anchorElement = fixture.debugElement.query(By.css('a')).nativeElement.textContent;


    // after assigning values to subsections, detect changes. this is async call.
    fixture.detectChanges();

    expect(component.subsections).toContain(anchorElement);
  });

Errors while running using npm test

ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'nativeElement' of null', '; Zone:', 'ProxyZone', '; Task:', 'setTimeout', '; Value:', TypeError{__zone_symbol__currentTask: ZoneTask{zone: Zone{_properties: ..., _parent: ..., _name: ..., _zoneDelegate: ...}, runCount: 0, _zoneDelegates: null, _state: 'notScheduled', type: 'macroTask', source: 'setTimeout', data: Object{handleId: ..., isPeriodic: ..., delay: ..., args: ...}, scheduleFn: function scheduleTask(task) { ... }, cancelFn: null, callback: function () { ... }, invoke: function () { ... }}}, 'TypeError: Cannot read property 'nativeElement' of null

ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'triggerEventHandler' of null', '; Zone:', 'ProxyZone', '; Task:', 'setTimeout', '; Value:', TypeError{__zone_symbol__currentTask: ZoneTask{zone: Zone{_properties: ..., _parent: ..., _name: ..., _zoneDelegate: ...}, runCount: 0, _zoneDelegates: null, _state: 'notScheduled', type: 'macroTask', source: 'setTimeout', data: Object{handleId: ..., isPeriodic: ..., delay: ..., args: ...}, scheduleFn: function scheduleTask(task) { ... }, cancelFn: null, callback: function () { ... }, invoke: function () { ... }}}, 'TypeError: Cannot read property 'triggerEventHandler' of null
    at Object.click (http://localhost:9876/_karma_webpack_/webpack:/testing/index.ts:39:8)
    at Object.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/navbar/navbar.component.spec.ts:62:5)
    at step (http://localhost:9876/_karma_webpack_/main.bundle.js:257:23)
    at Object.next (http://localhost:9876/_karma_webpack_/main.bundle.js:238:53)
    at http://localhost:9876/_karma_webpack_/main.bundle.js:232:71
    at new ZoneAwarePromise (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:729:1)
    at webpackJsonp../src/app/components/navbar/navbar.component.spec.ts.__awaiter (http://localhost:9876/_karma_webpack_/main.bundle.js:228:12)
    at Object.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/navbar/navbar.component.spec.ts:57:65)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:334:1)

These error I am getting, please help to resolve and suggest what i can do to resolve this.

I can share my package json file also. please guide me as I am new in this area. I am running all one npm test and the above error are coming. This spec file was there in project.I did not write this. I am only trying to execute test case. For any more information, please reply help and help.

How to use sinon.match with regex

Simple enough question - I'm testing JavaScript, and trying to assert that a datetime is correctly formatted.

Here're the variables:

let regexp = /^["']?d{4}-d[0-2]-[0-3]dT[0-2]d:[0-6]d:[0-6]d["']?/;
let dateToAssert = "2019-12-11T16:48:59";

Now I need to use something like sinon.match(regexp, dateToAssert);.

But:

sinon.assert.match(regexp, dateToAssert); returns AssertError: expected value to match

sinon.match(regexp, dateToAssert); returns Error: Timeout of 2000ms exceeded.

How do I tell the function to compare as regex and not as string? The first place I looked was the sinon documentation, but all I can find is

sinon.match(regexp);
Requires the value to be a string and match the given regular expression.

Why is there only one parameter? How is the program supposed to know what it's comparing the regex against?

Anyone prepared to help me out with the correct syntax here?