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