lundi 19 avril 2021

How to test react hooks using jest and mock? My unit test isn't working

I'm trying to write a test for my LED hook, but it's not working. I need to test if the code is calling the Set Behavior. I'm using toHaveBeenCalled, but I'm missing something.

When I run the test shows this message:

useLED › should call setBehavior()

    expect(jest.fn()).toHaveBeenCalled()

What I need to do? Please someone help me!!! Thank you.

My hook:

const useLED = (page: ICMSDataErrorPage | ICMSSuccessPage | undefined) => {
  const ledService = useService<ILEDService>(LEDServiceConstants.ServiceName);

  const startLEDAnimation = async () => {
    await ledService.startAnimation();
  };
  const stopLEDAnimation = async () => {
    await ledService.stopAnimation();
  };

  useEffect(() => {
    if (page) {
      const { red, green, blue, white, behavior } = page;

      ledService.setColor({
        red,
        green,
        blue,
        white,
      });
      ledService.setBehavior(behavior);
      startLEDAnimation();
    }
    return () => {
      stopLEDAnimation();
    };
  }, []);
};

export default useLED;

MY TEST:

describe("useLED", () => {
  let ledService : ILEDService;
  let page: ICMSDataErrorPage | ICMSSuccessPage | undefined;
  beforeEach(() => {
    ledService = mock<ILEDService>();
    page = mock<ICMSDataErrorPage | ICMSSuccessPage | undefined>();
    when(useService as jest.Mock)
      .calledWith(LEDServiceConstants.ServiceName)
      .mockReturnValue(ledService)
  });
  it("should call setBehavior()", () => {
    renderHook(() => useLED(page));
    expect(ledService.setBehavior).toHaveBeenCalled();
})});

junit does not appear even after adding the dependency in pow.xml

i'm learning java with springboot and i can't use junit annotations in my classes.

when I put @RunWith (SpringRunner.class) or @ExtendWith (SpringExtension.class) it doesn't even appear Cannot solve symbol as if I hadn't added the dependency in pow.xml, follow the full pow.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.fquadros</groupId>
    <artifactId>minhasfinancas</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>minhasfinancas</name>
    <description>Projeto para gerenciamento de finanças pessoais</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
        <!-- Dependencia para poder rodar testes feitos em Junit 4 -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

I'm using the IDE: Intelij 2018.2.8

what I've tried to do:

after I added the dependencies I went to build / rebuild Project

in the intelij terminal i already did the mvn clean commands and then the mvnInstall

at the time of installation I get several errors:

https://codepen.io/flavionfg/full/KKaQVbG

to use junit do i need to do anything other than that?

thanks in advance!

How to read a JSON for just one time and use it many time in the same robot file in Robot Framework

I am implementing a test automation framework with using robot framework. But i couldn't manage some JSON things.. I have a robot file full of keywords (no tests), i tried to read the json file (with full of xpaths) in test setup section, but it failed.

Is it possible to read the file at the beginning of a robot file and use that object for every keyword in that list?

Current structure:

keyword 1
  read json
  do sth

keyword 2
  read json
  do sth

keyword 3
  read json
  do sth

What i want?

read json

keyword 1
  do sth
keyword 2
  do sth
keyword 3
  do sth

How to raise timeout error in unittesting

This is first time i am touching ruby, so no sure about correct terminology. I have tried searching for mulitple things, but couldn't find a solution.

I have this code block

domain_response = MyDomain::Api::MyApi::Api.new(parameters: message.to_domain_object, timeout: 1000)
# :nocov:
case (response = domain_response.response)
when MyDomain::Api::MyApi::SuccessResponse
  ## do something
when Domain::ErrorResponses::TimeoutResponse
  ## do something.

now i am trying to testing TimeoutResponse, I have written(tried) this

      it "when api call timesout" do
        expect(MyDomain::Api::MyApi::Api).to{
          receive(:new)
        } raise_error(MyDomain::ErrorResponses::TimeoutResponse)
      end

this gave me error that unexpected identifier.

I have also tried by not providing receive, and it gave me error that block is expected.

Whats the proper way to raise an error that i can test?

How to add query param to send request url using a pre request script postman?

I would like to be able to add a query param to the pre request script sendRequest url shown below, but havent been able to figure out how to do that.... I have tried to use different options to no avail. Thanks for the help!

pm.sendRequest({
        url: pm.globals.get("base_url") + bankNum + "/loans/" + loan14,
        method: 'GET',
        header: {
        'Authorization': '********',
        },
    }, function (err, response) {
        console.log(response.json());
    });

What is the best way to await functions in UI testing in Android Studio without Thread.Sleep()?

I'm using Espresso to write some automated tests for an Android app that I've developed. All the tests are automated and are passing/failing according to what happens with the UI. I've ran the code through SonarQube to detect bad coding practices and it's informed me that Thread.Sleep() should not be used.

I'm mainly using Thread.sleep() in instances where I'm typing out a form and need to hide the keyboard to scroll down to tap the next form field etc. From my understanding, using something like awaitility is for big async functions like fetching data etc. but what should I use in my case where something is not being fetched but more so for just interacting with the UI?

Here is an example of a log in test that I have created that uses Thread.Sleep():

        onView(withId(R.id.fieldEmail)).perform(typeText("shelley@gmail.com"));
        Thread.sleep(SHORT_WAIT);
        onView(withId(R.id.fieldPassword)).perform(click());
        onView(withId(R.id.fieldPassword)).perform(typeText("password"));
        Thread.sleep(SHORT_WAIT);
        onView(isRoot()).perform(pressBack());
        Thread.sleep(SHORT_WAIT);
        onView(withId(R.id.signIn)).perform(click());
        Thread.sleep(LONG_WAIT);

jest/enzym expect.any(ReactComponent)

may be some of you faced with testing features when need to check specification. I am faced with want to test files of themes which look like some thing like this.

export { ReactComponent as SVG1 } from './svg1.svg';
export { ReactComponent as SVG2 } from './svg2.svg';
// ... etc

I was find the way how to check... But it doesn't provide 100% sure it's will be React Component.

const ReactComponent = expect.any(Function);

const svgSchema = expect.objectContaining({
  SVG1: ReactComponent,
  SVG2: ReactComponent,
});

May be some who knows how to define more smart/elegant solution ?

P.S. I do not want to test @svgr/webpack functionality. Within project will be a lot of different themes and i want to make sure they contain required SVG for each theme

How to create complex Integration Test with 2 Web API using C# (NUnit)?

I have an application that works as shown on the figure:

My app scheme

The idea behind is:

Both Web API (Web API #1, Web API #2) are part of my application (2 projects in 1 solution).

step 1: Requesting the endpoint of Web API #1. Web API #1 stores a record to database with status NEW.

step 2: Web API #1 returns a response to a caller (For example: Your request has been accepted).

step 3: Web API #1 has a demon inside. The demon sees a new record in the database with status NEW and make a request to Web API #2.

step 4: Web API #2 do some work (For example: 10 seconds) and returns a response to Web API #1. Web API #1 updated the record in database with status PROCESSED.

I know how to test the endpoint of Web API #1 (WebApplicationFactory etc...), but I want to test full cycle: request to Web API #1 -> record with status NEW -> request to Web API #2 -> response -> record with status Processed -> We have record with status PROCESSED? => Test is done.

iPad / iPhone: Slow down application start time for testing purpose

Could someone advice any tools / techniques in order to slowdown application start time on iOS device. Most articles are focused around performance improvement, however I am interested in opposite scenario.

How to interact with Angular ColorPicker components using Selenium WebDriver?

How to interact with Angular ColorPicker components using Selenium WebDriver? There's no text field input for hex codes, and it's operated purely by mouse clicks. An example of it can be seen here: https://www.primefaces.org/primeng/showcase/#/colorpicker

pytest fails due to ModuleNotFoundError, but works when using "python -m pytest"

Similarly to this OP's issue, but the other way around, pytest works for me within my virtual environment ("venv") only when running python -m pytest, but not with just running pytest in my console.

I'm working with VS Code on Windows 10 within the built-in console.

The command pytest does not work in neither scenario: neither in the global scope, nor in the target venv. By contrast, python -m pytest works within said venv.

I'm working with CLI from the root directory of the project whose full directory tree is:

(Testing) PS C:\Users\user\Documents\Programming\Testing> tree /F
Folder PATH listing for volume Windows
Volume serial number is 50BE-501E
C:.
│   default_python_script.py
│
├───.benchmarks
├───.pytest_cache
│   │   .gitignore
│   │   CACHEDIR.TAG
│   │   README.md
│   │
│   └───v
│       └───cache
│               lastfailed
│               nodeids
│               stepwise
│
├───.vscode
│       launch.json
│       settings.json
│
├───cli_testapp
│   │   cli_testapp.py
│   │   __init__.py
│   │
│   └───__pycache__
│           cli_testapp.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───my_sum
│   │   my_sum.py
│   │   __init__.py
│   │
│   └───__pycache__
│           my_sum.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───tests
│   │   errors_pytest.log
│   │   test.py
│   │   testing.py
│   │   test_with_pytest.py
│   │
│   ├───.benchmarks
│   ├───.pytest_cache
│   │   │   .gitignore
│   │   │   CACHEDIR.TAG
│   │   │   README.md
│   │   │
│   │   └───v
│   │       └───cache
│   │               lastfailed
│   │               nodeids
│   │               stepwise
│   │
│   └───__pycache__
│           test.cpython-39.pyc
│           testing.cpython-39.pyc
│           test_with_pytest.cpython-39-pytest-6.2.3.pyc
│           test_with_pytest.cpython-39.pyc
│
└───__pycache__
        test.cpython-39.pyc
        testing.cpython-39.pyc

What's annoying about it is that I'd like to use the helpful VS Code testing kit, which facilitates employing any testing framework, also pytest. The problem is that VS Code uses the following command by default to run the testing:

python c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir c:\Users\user\Documents\Programming\Testing -s tests

As one can inspect, it uses pytest instead of python -m pytest. Apparently, the default way of implementation via VS Code doesn't load correctly the environmental variables, since it always produces the following error:

Test Discovery failed:
Error: ============================= test session starts =============================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: c:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 0 items / 1 error

=================================== ERRORS ====================================
_________________ ERROR collecting tests/test_with_pytest.py __________________
ImportError while importing test module 'c:\Users\user\Documents\Programming\Testing\tests\test_with_pytest.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\.pyenv\pyenv-win\versions\3.9.0a4\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_with_pytest.py:22: in <module>
    from cli_testapp import cli_testapp
E   ModuleNotFoundError: No module named 'cli_testapp'
=========================== short test summary info ===========================
ERROR tests/test_with_pytest.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
==================== no tests collected, 1 error in 0.23s =====================

Traceback (most recent call last):
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\pytest\_discovery.py", line 44, in discover
    raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 2)

For the sake of completeness, I'm going to post how it looks like with python -m pytest within the venv correctly loaded (CLI utilized here):

(Testing) PS C:\Users\user\Documents\Programming\Testing> python -m pytest
=================================================================== test session starts ===================================================================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: C:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 7 items

tests\test_with_pytest.py .F....F                                                                                                                    [100%]

======================================================================== FAILURES =========================================================================
____________________________________________________________________ test_always_fails ____________________________________________________________________

    def test_always_fails():
        """Function docs:\n
        See above with function docs of "test_always_passes()".
        """
>       assert False
E       assert False

tests\test_with_pytest.py:46: AssertionError
______________________________________________________________ test_initial_transform[dict] _______________________________________________________________

generate_initial_transform_parameters = ({'city': 'Anytown', 'name': ...})

    def test_initial_transform(generate_initial_transform_parameters):
        test_input = generate_initial_transform_parameters[0]
        expected_output = generate_initial_transform_parameters[1]
>       assert cli_testapp.initial_transform(test_input) == expected_output
E       AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
E         Omitting 5 identical items, use -vv to show
...

tests\test_with_pytest.py:118: AssertionError
================================================================= short test summary info =================================================================
FAILED tests/test_with_pytest.py::test_always_fails - assert False
FAILED tests/test_with_pytest.py::test_initial_transform[dict] - AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
=============================================================== 2 failed, 5 passed in 0.31s ===============================================================

How can I resolve this issue that it'll always work, also with just pytest? This is particularly important, because I'd love to leverage the amenities provided by VS Code, which employs a default command based on just pytest.

How to combine different testInstrumentationRunner

Is there any way to have different testInstrumentationRunner for each test? Do I have to create a Task for it? I have my runner as follows :

class MyTestRunner : AndroidJUnitRunner() {
    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, MyTestApp::class.java.name, context)
    }
}

But what if I want to run some using the real app? how can I choose it?

I've been reading that is possible doing it with @RunWith(AndroidJUnit4ClassRunner::class)on my tests I'm using it but I understand if I do this it takes the one of the defaultConfig

defaultConfig {
        testInstrumentationRunner("mypackage.MyTestRunner")
}

But I can not use something like

@RunWith(MyTestRunner::class)

In case I could do this I'd understand how can I use different runners.

Unable to interact with dropdown using CCS selector

I'm Currently trying to work with a dropdown on Testcafe. I have been struggling to interact with this please see error message provided: 1) The specified selector does not match any element in the DOM tree. > | Selector('.rtv-specialties.btn')

What I'm trying to select ^ arrow

Style sheet

<div class="col-md-6  rtv-specialties"><!--!-->
    <div class="form-group"><!--!-->
                <label class="col-form-label col-form-label-sm  dxbs-fl-cpt" for="Specialties"><!--!-->
                    Specialty<!--!-->
                </label><!--!-->
                <!--!--><!--!-->
                    <div class="dxbs-fl-ctrl"><!--!--><!--!--><!--!--><!--!-->

<div id="ide2d65ebf-ef95-4339-99b5-5f45b4d24c06" class="dxbs-dropdown-edit dxbs-combobox  valid" _bl_401af617-1215-41ca-8a5e-05f4d6d1c311="" data-dispose-id="63754436394711968"><!--!-->
    <!--!--><!--!--><!--!--><div class="input-group input-group-sm dx-listbox"><!--!-->
    <!--!--><!--!-->
        <!--!-->
    <!--!-->
    <div><!--!-->
        <!--!-->
            <!--!--><!--!-->
        <!--!-->
        <input id="Specialties" name="idc97c1635-39d6-4393-ad3c-173d858afa80" type="text" class="form-control form-control-sm dxbs-form-control text-truncate dx-reset-readonly-style" autocomplete="off" readonly="" placeholder="Choose..." data-blured-class="form-control form-control-sm dxbs-form-control dx-reset-readonly-style text-truncate" data-focused-class="form-control form-control-sm dxbs-form-control dx-reset-readonly-style text-truncate" _bl_f4380398-d403-43bb-b216-7f347c17e16d="" style="padding-right: 46.6px;"><!--!-->
        <!--!-->
        <!--!-->
    </div><!--!-->
        <div class="form-control form-control-sm input-group-append dxbs-input-group-append dxbs-focus-hidden" _bl_c0f56011-62d0-48f0-8006-939ec5ba268d=""><!--!-->
            <!--!--><span class="dxbs-feedback "><!--!-->
    <!--!--><!--!--><!--!-->        <button class="btn btn-sm dx-btn dxbs-edit-btn dxbs-clear-btn" id="id09de5a6a-83af-440b-845d-dd975b127628" aria-label="Clear value" tabindex="-1" type="button"><!--!-->
            <!--!-->
        <!--!--><svg class="dx-blazor-clear-button-icon" role="img">
            <use href="#dxsc-clear-button-icon"></use>
        </svg>
    <!--!-->
        </button><!--!-->
<!--!-->
</span><!--!-->
            <!--!-->
            <!--!--><!--!--><!--!-->        <button class="btn btn-sm dx-btn  btn-secondary dxbs-edit-btn dropdown-toggle dxbs-dropdown-toggle" id="id2886515b-19cf-4d4f-b553-534352486075" data-toggle="dropdown-show" aria-haspopup="true" aria-expanded="false" aria-label="Open or close the drop-down window" tabindex="-1" type="button"><!--!-->
            <!--!-->
<!--!-->
                    <span></span><!--!-->
        <!--!-->
        </button><!--!-->
<!--!-->

How to run load test for 3000 users with 50 loops in jmeter?

I tried to run a load test in jmeter with 3000 users and 50 loops.But it shows this error.

[9.746s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 4k, detached.
Uncaught Exception java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached in thread Thread[StandardJMeterEngine,5,main]. See log file for details.

I also tried to increase the Heap size using- HEAP:="-Xms2g -Xmx2g -XX:MaxMetaspaceSize=2g"

But the same issue of OutOfMemory persits. Thanks for the help

ReactJS :: Jest Testing :: "TypeError: Cannot read property 'then' of undefined"

I am currently having some trouble compiling a test for an online study task to see whether the fetch() function of my weather application is working correctly.

I have made use of the useEffect() hook to fetch the data from the OpenWeather API to store and render once the API's URL changes.

I am new to Jest testing and have tried a couple of things, following tutorials and other sources, but am unfortunately not having any success. My current solution is returning the following error: "TypeError: Cannot read property 'then' of undefined"

Please see below my code:

App.js

// Imported hooks and react libraries.
import React, { useState, useEffect } from 'react';
// Imported stylesheet.
import './App.css';
// Imported components.
import Header from './components/Header';
import Footer from './components/Footer';
// Imported countries from i18n-iso-countries to get the iso code and return the country name in English.
import countries from 'i18n-iso-countries';
// Imported icons from Font Awesome.
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCloudSunRain,
  faHandHoldingWater,
  faHandSparkles,
  faMapMarkerAlt,
  faSearchLocation,
  faTemperatureHigh,
  faTemperatureLow,
  faWind
} from '@fortawesome/free-solid-svg-icons';

countries.registerLocale(require('i18n-iso-countries/langs/en.json'));

function App() {
  // Setting the initial states of the app to store the response and the locations. Using the useState hook to set the data. Showing Durban as 
  // an example.
  const [apiData, setApiData] = useState({});
  const [getState, setGetState] = useState('Durban');
  const [state, setState] = useState('Durban');

  // Constructing the API URL and accessing the key via the process.env variable.
  const apiKey = process.env.REACT_APP_API_KEY;
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${state}&APPID=${apiKey}`;
  console.log (process.env.REACT_APP_API_KEY);

  // Using the useEffect hook to fetch the data from the API to store and render once the API's URL changes.
  useEffect(() => {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => setApiData(data));
  }, [apiUrl]);

  // Constructed an input handler to get the data once requested and to store in the getState.
  const inputHandler = (event) => {
    setGetState(event.target.value);
  };

  // Constructed a submit handler to handle the request once the search button is clicked.
  const submitHandler = () => {
    setState(getState);
  };

  // Constructed a kelvin to celsius converter to output the temperature in celsius.
  const kelvinToCelsius = (k) => {
    return (k - 273.15).toFixed(2);
  };

  // Constructed a miles to kilometers converter to output the temperature in kilometers.
  const milesToKilometers = (k) => {
    return (k * 3.6).toFixed(2);
  };

  // Created a function to capitalize the first letters of each part of the countries' names.
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  };

  // Returning the data. Included the React Bootstrap stylesheet's link and called the "Header" and "Footer" components below. I also called the
  // following from the API:

  // {apiData.weather[0].icon} - The icon displaying the current conditions.
  // {apiData.name} - The city's name.
  // {countries.getName(apiData.sys.country, 'en', { select: 'official', })} - The country's name with the first letters capitalized.
  // {kelvinToCelsius(apiData.main.temp_min)} - The minimum temperature.
  // {kelvinToCelsius(apiData.main.temp_max)} - The maximum temperature.
  // {kelvinToCelsius(apiData.main.feels_like)} - The "feels like" temperature, taking into account the temperatures and conditions.
  // {apiData.weather[0].main} - The summarized condition.
  // {capitalizeFirstLetter(apiData.weather[0].description)} - The full condition's description.
  // {apiData.main.humidity} - The humidity percentage.
  // {milesToKilometers(apiData.wind.speed)} - The wind speed.

  // Called the inputHandler (input section) and submitHandler (button) to get the current state's values and added Font Awesome icons. Also 
  // added a loading message for if the page load takes a while. Currently only shows if there is no input or upon refresh.
  return (
    <div className="App">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"></link>
      <Header />

      <div className="container">
        <div className="searchsection">
          <label htmlFor="location-name">Enter Location:</label>
          <input
            type="text"
            id="location-name"
            onChange={inputHandler}
            value={getState}
          />
          <button onClick={submitHandler}><FontAwesomeIcon icon={faSearchLocation} /></button>
        </div>

        <div className="mt-3 mx-auto" style=>
          {apiData.main ? (
            <div id="weathercontainer">
              <div id="mainweather">
                <img
                  src={`http://openweathermap.org/img/wn/${apiData.weather[0].icon}@2x.png`}
                  alt="weather status icon"
                  className="weather-icon"
                />
                <p className="h2">{kelvinToCelsius(apiData.main.temp)}&deg;C</p>
                <h3><FontAwesomeIcon icon={faMapMarkerAlt} /> {apiData.name}</h3>
                <h3>{countries.getName(apiData.sys.country, 'en', { select: 'official', })}</h3>
              </div>

              <div className="temperatureconditions">
                <div id="temperature">
                  <h5>Temperature:</h5>
                  <p><FontAwesomeIcon icon={faTemperatureLow} /> {kelvinToCelsius(apiData.main.temp_min)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faTemperatureHigh} /> {kelvinToCelsius(apiData.main.temp_max)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faHandSparkles} /> Feels like: {kelvinToCelsius(apiData.main.feels_like)}&deg;C</p>
                </div>
                <div id="conditions">
                  <h5>Conditions:</h5>
                  <p><FontAwesomeIcon icon={faCloudSunRain} /> {apiData.weather[0].main}: {capitalizeFirstLetter(apiData.weather[0].description)}</p>
                  <p><FontAwesomeIcon icon={faHandHoldingWater} /> Humidity: {apiData.main.humidity}%</p>
                  <p><FontAwesomeIcon icon={faWind} /> Wind Speed: {milesToKilometers(apiData.wind.speed)} km/h</p>
                </div>
              </div>
            </div>
          ) : (
            <h1 id="loading">Weather Bot is Loading...</h1>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
}

// Exported App to Index.js.
export default App;

App.Fetch.React.test.js

import React from 'react';
import App from '../App';
import { render, screen, act } from '@testing-library/react';

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () =>
            Promise.resolve({
                value: "Durban"
            }),
    })
);

describe("App", () => {
    it("loads Durban city name", async () => {
        await act(async () => render(<App />));
        expect(screen.getByText("Durban")).toBeInTheDocument();
    });
});

Does anyone mind helping?

Can mechanical engineering experience count in IT field as Software developer?

I'm mechanical engineer and I want to work at IT company as a 'Software developer'. I've 2Years experience in mechanical industry, So can this experience should be counted in IT Company?

How to Upload txt file with Cypress for API Testing - XMLHTTPRequest?

I'm trying to test an endpoint which will upload a file and give 200 response status code in cypress. As per some research cy.request cannot be used to upload a file for multipart/form-data so we need to use XMLHttp to upload such files. I have created below file to test the api but it doesn't work. Can someone please help what's wrong with my code ? Thank you.

Added below code under support/commands.ts(I will require a header to pass token from auth endpoint)

// Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data)
Cypress.Commands.add('form_request', (method,URL, formData,headers, done) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, URL);
        xhr.setRequestHeader("accept", "application/json");
        xhr.setRequestHeader("Content-Type", "multipart/form-data");
    if (headers) {
        headers.forEach(function(header) {
            xhr.setRequestHeader(header.name, header.value);
        });
    }
        xhr.onload = function (){
            done(xhr);
        };
        xhr.onerror = function (){
            done(xhr);
        };
        xhr.send(formData);
})

Test file to call multipartFormRequest:

const fileName = 'test_file.txt';
                    const method = 'POST';
                    const URL = "https://fakeurl.com/upload-file";
                    const headers = api.headersWithAuth(`${authToken}`);
                    const fileType = "application/text";

                    cy.fixture(fileName, 'binary').then((res) => {
                        Cypress.Blob.binaryStringToBlob(res, fileType).then((blob) => {
                            const formData = new FormData();
                            formData.append('file', blob, fileName);

                            cy.multipartFormRequest(method, URL, headers, formData, function (response) {
                                expect(response.status).to.equal(200);
                            })
                        })

I'm getting this error message:- Cypress.Blob.binaryStringToBlob(...).then is not a function.

Mock Typeorm QueryBuilder

I need to test a call like this:

    const connection = await getConnection('default');
    const queryBuilder = connection
        .createQueryBuilder(Reading, 'r')
        .where("r.code = :code AND um = 'KWH'", { code: meter.code })
        .andWhere(" measure_date BETWEEN to_date(:startDate,'YYYY-MM-DD') AND to_date(:endDate,'YYYY-MM-DD')", {
            startDate,
            endDate,
        })
        .andWhere('r.deleted_at IS NULL')
        .orderBy('r.measure_date', 'DESC')
        .addOrderBy('r.reading_type')
        .addOrderBy('r.band', 'ASC');

    const readings = await queryBuilder.getMany();

i tried many solutions, but none worked. any suggestions?

thx to all

Testing service with http still gives provider not found while importing HttpClientTestingModule

I'm starting making tests for my Angular project but get stuck with some problems while testing my service which is using HTTP.

Bases on other discussion I've already imported the HttpClientTestingModule but I still get a error that the provider is not found..

My code currently looks like:

import { TestBed } from '@angular/core/testing';
import {
  HttpClientTestingModule,
} from '@angular/common/http/testing';

import { AuthenticationService } from './authentication.service';

describe('AuthenticationService', () => {
  let service: AuthenticationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
    });
    service = TestBed.inject(AuthenticationService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

And the given error while running the code is:

NullInjectorError: R3InjectorError(DynamicTestModule)[ErrorInterceptor -> AuthenticationService -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11049:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11216:1)
...

I hope someone knows what to do.

Specflow step file doesn't appear to be recognised by feature file

I created a Specflow project which has one feature file, EBIntegrationTest.feature :

Feature: EBIntegrationTest for MF
    Initial test feature

@mytag
Scenario: Subscribe to Market Data EU Topic and write to SQL DB
    Given MD messages are streaming to MF application
    When MF enriches template 304
    Then the enriched messages are then written to an SQL DB server

I then added a step file to my Steps folder:

using System;
using System.Collections.Generic;
using System.Text;

namespace eb_test_tool.Steps
{
    class EBIntegrationTest
    {
        [Given(@"MD messages are streaming to MF application")]
        public void GivenMDMessagesAreStreamingToMFApplication()
        {
            var processInfo = new ProcessStartInfo("C:\\ProgramData\\CME\\Java_SymLinks\\JDK8_x64\\jre\\bin\\java.exe",
                                                   "java -jar .\\Jar\\Injector\\MD-Injector-1.0.jar My.TOPIC")
            {
                CreateNoWindow = true,
                UseShellExecute = false
            };
            Process proc;

            if ((proc = Process.Start(processInfo)) == null)
            {
                throw new InvalidOperationException("Message injector failed to run");
            }

            proc.WaitForExit();
            int exitCode = proc.ExitCode;
            proc.Close();
        }
        
        [When(@"MF enriches template (.*)")]
        public void WhenMFEnrichesTemplate(int p0)
        {
            ScenarioContext.Current.Pending();
        }
        
        [Then(@"The enriched messages are then written to an SQL DB server")]
        public void ThenTheEnrichedMessagesAreThenWrittenToAnSQLDBServer()
        {
            ScenarioContext.Current.Pending();
        }

    }
}

When I run dotnet test it is skipped with this alert:

enter image description here

Am I doing something wrong or should I reference my steps file from the feature file in some way?