lundi 1 octobre 2018

How to test React-Leaflet map component

I have little knowlegde when it comes to test React Components, so I'm sorry in advance for this question.

I developed a map component that is working, but I would like to perform some tests, just to make sure everything is running smoothly.

I tried the most simple example:

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<BikeMap />, div);
  ReactDOM.unmountComponentAtNode(div);
});

But I get an error:

enter image description here

What other tests should I perform for this map component?

Here's the map component:

import React, { Component } from 'react';
import L from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';
import 'react-leaflet-markercluster/dist/styles.min.css';


// code for map marker icon
var myIcon = L.icon({
    iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3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btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=',
    iconSize: [25, 41],
    iconAnchor: [12.5, 41],
    popupAnchor: [0, -41]
});

export default class BikeMap extends Component {
    constructor(props) {
    super(props);
        this.state = {
            location: {
              lat: 51.505,
              lng: -0.09,
        },
        bikeData: [],
        isLoading: true,
        haveUsersLocation: false,
        zoom: 3
    }
}

//code for loading
componentWillMount() {
    setTimeout(() => this.setState({
        isLoading: false
    }), 2000);
}

componentDidMount() {
    //code to get the bike information
    fetch('https://api.citybik.es/v2/networks')
        .then(res => {
            if (!res.ok) {
                throw new Error(res.status);
            }
            return res.json();
        })
        .then(response => {
            const networkData = response.networks;
            this.setState({
                bikeData: networkData
            });
        })
        .catch(error => {
            console.log(error);
        });

    //code to get the user's location(if so desires)
    navigator.geolocation.getCurrentPosition((position) => {
        this.setState({
            location: {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            },
            haveUsersLocation: true,
            zoom: 6
        });
    }, () => {
        console.log('Uops! The user didnt give its location!');
        fetch('https://ipapi.co/json')
            .then(res => {
                if (!res.ok) {
                    throw new Error(res.status);
                }
                return res.json();
            })
            .then(location => {
                this.setState({
                    location: {
                        lat: location.latitude,
                        lng: location.longitude
                    },
                    haveUsersLocation: true,
                    zoom: 13
                });
            })
            .catch(error => {
                console.log(error);
            })
    });
}


render() {
    const { isLoading } = this.state;
    const position = [this.state.location.lat, this.state.location.lng]
    const bikeData = this.state.bikeData;

    if (isLoading) {
        return <div className="spinner"></div>
    }

    return (
        <Map className="map markercluster-map" center={position} zoom={this.state.zoom}>
            <TileLayer
                attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <MarkerClusterGroup>
                {
                    bikeData && bikeData.map((data, index) => {
                        const company = data.company;
                        if (company) {
                            const companyList = company.map((station, index) => {
                                return (
                                    <div key={index}>{station}</div>
                                )
                            })
                            return (
                                <Marker
                                    icon={myIcon}
                                    key={data.id}
                                    position={[data.location.latitude, data.location.longitude]}>
                                    <Popup>
                                        <b>City:</b> {data.location.city} <br />
                                        <b>Country:</b> {data.location.country} <br />
                                        <b>Name of Network:</b> {data.name} <br />
                                        <b>Number of Stations:</b> {data.company.length} <br />
                                        <b>Name of Stations:</b> {companyList}
                                    </Popup>
                                </Marker>
                            )
                        }
                        return <div key={index}>No Data</div>
                    })
                }
            </MarkerClusterGroup>
        </Map>
    )
}
}

Thank you!

Javascript tests: Inconsistent number of tests

Apologies if this is somewhat vague (and it is), but I've inherited a bit of a mess from a departed contractor, and need some pointers...

I've got (inherited) a number of JavaScript Unit tests (approx. 770+). These are being run with Chutzpah (both in Visual Studio 2015, and from the command line during our Team City build).

The problem is, each time I run the tests - either in VS, or from the command line - the total number of tests run differs, as does the number of failures

It's the inconsistency that's the problem. I can't start investigating actual problems, as I don't even know if I can trust the tests that have been run.

Apologies, I appreciate I've not given any real detail here, but can anyone suggest any high level things I should look into in this sort of scenario ?

Cheers

Appium Configuration Java

Im trying to automize my App using Appium, but I can't seem to get the configuration right.

Appium Server is running on 127.0.0.1:4723 and started. I emulate a Device using the Android SDK emulator with avd.Im using Eclipse with Selenium and TestNG to test my configuration.

What I get is an Error in the @BeforeMethod

FAILED CONFIGURATION: @BeforeMethod setUp
java.lang.NoClassDefFoundError: org/openqa/selenium/logging/LoggingHandler

Any Suggstion what might be wrong in my configuration?

package xxx_appium.xxx_appium_test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.aspectj.lang.annotation.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.service.DriverCommandExecutor;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import bsh.Capabilities;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

public class ConnectionTest {

@BeforeMethod
public void setUp() throws MalformedURLException {

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("BROWSER_NAME", "Android");
    capabilities.setCapability("avd","ANexus");
    capabilities.setCapability("deviceName", "ANexus");
    capabilities.setCapability("platformName", "Android");
    capabilities.setCapability("platformVersion", "9");
    capabilities.setCapability("app", 
    "C:\\Users\\xxx\\Downloads\\yyyy.apk");

    driver = new AndroidDriver<WebElement>(new         
    URL("http://localhost:4723/wd/hub"), capabilities);

}
@AfterMethod
public void tearDown() {
    driver.quit();
}

@Test
public void sampleTest() {
}

Protactor E2E: Check if a new window is displayed or get the new window url

i have some troubles with the following test:

it('Should verify new window url', function () {
    page.list.get(0).click().then(function () {
        browser.getAllWindowHandles().then(function (handles) {
            newWindowHandle = handles[0];
            browser.switchTo().window(newWindowHandle).then(function () {
            expect(browser.getCurrentUrl()).toMatch(/\/url/);
            });
        });
    });
});

I get this error: Cannot read property get of undefined.

Java Eclipse - Expect browser binary location

I am trying to run the following Java Code:

package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class sekcija9 {

    public static void main(String[] args) {        
        System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Mozilla Firefox\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
    }
}

I am getting the following error:

Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line

I am using:

  1. Firefox 62.0.2 64bit

  2. Selenium 3.3.1

  3. GeckoDriver 0.22.0 (latest)

I have looked here: link

Do I need to downgrade Firefox version? If not, how can I resolve this issue without downgrade?

Android gradle androidTestApi & testApi configuration obsoleted

I got 2 modules, module A and module B. Module B depends on module A when module A shares dependency libraries to module B by using api configuration.

When setting up test environment, inside module A, I also use testApi & androidTestApi to make module B uses shared testing libraries. However, after running gradle sync, I got warning message: WARNING: Configuration 'testApi' is obsolete and has been replaced with 'testImplementation'.

Read the provided link and it said that other modules can't depend on androidTest, you get the following warning if you use the androidTestApi configuration. Therefore, I must define test libraries in module B in my example for skipping this warning.

I have some questions on this situation:

  1. Why one module should not depends on testing dependencies of other module, although it can depend on normal dependencies defined as api?
  2. Do we have anyway to force module B depends on test libraries of module A without defined these libraries again in module B?

Many thanks

Set postgres database url on travis-ci for testing node.js application

I have written some tests for my node.js application and the tests are running locally using a Postgresql test database.

When I run my test script, npm run test, the environment is set to test and when this happens, the database connection string is set for the test database and my queries in the application are now done on the test database. Like so:

let connectionString;
if (process.env.NODE_ENV === 'test') {
  connectionString =`postgresql://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.TEST_DB_NAME}`;
} else {
  connectionString =`postgresql://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`;
}

This way my tests are being run on the test database.

On travis however, I know I am going to need to further configure its own database. On the travisCI docs, I read about how I could set up a PostgreSQL database here, but this doesn't help me because how do I get the full database URL as above? On travisCI, what am I to use as my database hostname or port and how do I set this value inside my code?

How do I set the database connection string and access it in my code?

Thanks for any ideas.