jeudi 28 février 2019

What can developers do to assist in automation testing?

The company I work for is starting a new web application, and I have requested that front end developers make this application Automation Friendly.

The previous application was using the react framework, very few elements had unique ID's (or any unique identifier at all). This time around, I have asked the developers to include a custom data attribute, specifically for automation.

I am looking for anyone who may have experience in this kind of situation.

  1. What have you asked your developers to do to assist in automation?
  2. Are there any standards, or guidelines for naming elements in an application to suit Selenium automation?
  3. are custom data attributes the best way to go? are there other options?

Any advice/guidance would be greatly appreciated!

Not able to create jar from develop branch

I am also facing issue of "Exception in thread "main" java.lang.StackOverflowError"

https://github.com/intuit/karate/issues/661

According to you,this has been fixed in version '1.0.0' in develop branch.

I am not able to create the jar from develop branch (As I am following these steps:-https://github.com/intuit/karate/wiki/Developer-Guide)

Please push this fix to master and release the new version or tell me how to create jar.

What I did is:- git clone https://github.com/intuit/karate.git cd karate git checkout develop mvn clean install -P pre-release

After this I am getting this error:-

10:53:42.068 [main] DEBUG com.intuit.karate.XmlUtilsTest - map: {env:Envelope={_={env:Header=null, env:Body={_={QueryUsageBalanceResponse={_={Balance=null, Result={Success=null, Error={Category=DAT, Code=DAT_USAGE_1003, Description=Invalid Request: Invalid Input criteria: No asset found for license/eoc (630289335971198/855939)., Source=SIEBEL}}}, @={xmlns=http://www.intuit.com/iep/ServiceUsage/IntuitServiceUsageABO/V1}}}, @={xmlns=http://www.intuit.com/iep/ServiceUsage/IntuitServiceUsageABO/V1}}}, @={xmlns:S=http://schemas.xmlsoap.org/soap/envelope/, xmlns:env=http://schemas.xmlsoap.org/soap/envelope/}}}
[INFO] Tests run: 21, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.065 s - in com.intuit.karate.XmlUtilsTest
[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   RunnerTest.testRunningFeatureFromJavaApi:92 expected:<someValue> but was:<null>
[ERROR]   RunnerTest.testRunningRelativePathFeatureFromJavaApi:100 expected:<someValue> but was:<null>
[ERROR]   
ScriptTest.testFromJsKarateGetForJsonObjectVariableAndCallFeatureAndJs:1359
[ERROR] Errors: 
[ERROR]   ConfigTest.testSettingVariableViaKarateConfig:21 » Runtime javascript evaluati...
[INFO] 
[ERROR] Tests run: 242, Failures: 3, Errors: 1, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] karate-parent ...................................... SUCCESS [  0.342 s]
[INFO] karate-core ........................................ FAILURE [ 11.289 s]
[INFO] karate-apache ...................................... SKIPPED
[INFO] karate-junit4 ...................................... SKIPPED
[INFO] karate-junit5 ...................................... SKIPPED
[INFO] karate-netty ....................................... SKIPPED
[INFO] karate-gatling ..................................... SKIPPED
[INFO] karate-demo ........................................ SKIPPED
[INFO] karate-mock-servlet ................................ SKIPPED
[INFO] karate-jersey ...................................... SKIPPED
[INFO] karate-archetype ................................... SKIPPED

Angular: How to fire ngAfterViewChecked() for directive in test

I am writing test for a directive that implements the AfterViewChecked interface. I was following the test written for MatTooltip here I have created a demo component where I applied the directive under test. I read here that for change detection of the component fixture to work, I need to wrap the demo component into another host component, which I did, but it did not fire the ngAfterViewChecked() method of the directive. I can, off course, call the method myself, but it will kind of defeat the purpose of the test. Below is the code. Any help is appreciated. Thanks in advance.

The directive

@Directive({
  selector: '[scroll-into-view]',
})
export class ScrollIntoViewDirective implements AfterViewChecked  {
  private element: HTMLElement;
  @Input() parentContainer: HTMLElement | undefined;

  selected = false;

  constructor(private elRef: ElementRef) {
    this.element = elRef.nativeElement;
  }

  @Input('scroll-into-view') set elementSelected(condition: boolean) {
    this.selected = condition;
  }

  ngAfterViewChecked() {
    if (this.selected && !this.isWithinParent()) {
      this.element.scrollIntoView();
    }
  }          
}

The demo component

@Component({
  selector: 'wvc-scroll-into-view-demo',
  template: `
    <div #container>
      <div [scroll-into-view]="!!scrollIntoView" [parentContainer]="container">
        Test Div
      </div>
    </div>
  `,
})
class ScrollIntoViewDemoComponent {
  @Input() scrollIntoView?: boolean;
}

The host component

@Component({
  selector: 'wvc-scroll-into-view-demo-host',
  template: `
    <wvc-scroll-into-view-demo
      [scrollIntoView]="scrollIntoView"
    ></wvc-scroll-into-view-demo>
  `,
})
class ScrollIntoViewDemoHostComponent {
  scrollIntoView = false;
}

The test

describe('ScrollInViewDirective', () => {
  let fixture: ComponentFixture<ScrollIntoViewDemoHostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ScrollIntoViewDemoComponent,
        ScrollIntoViewDemoHostComponent,
        ScrollIntoViewDirective,
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ScrollIntoViewDemoHostComponent);
  });

  fit('should scroll element into view.', () => {
    const demoComponentDebugElement = fixture.debugElement.query(
      By.directive(ScrollIntoViewDemoComponent),
    );

    const directiveNativeElement = demoComponentDebugElement.query(By.directive(ScrollIntoViewDirective)).nativeElement;
    console.log(`Debug Element: ${demoComponentDebugElement.name}`);
    spyOn(directiveNativeElement, 'scrollIntoView');

    const directive = demoComponentDebugElement.injector.get<ScrollIntoViewDirective>(
      ScrollIntoViewDirective,
    );

    spyOn(directive, 'isWithinParent').and.returnValue(true);

    expect(directiveNativeElement.scrollIntoView).not.toHaveBeenCalled();

    fixture.componentInstance.scrollIntoView = true;

    fixture.detectChanges();

    expect(directiveNativeElement.scrollIntoView).toHaveBeenCalled();
  });
});

Hijack the it() that protractor provides

I need to hijack the it() that the protractor provides to this:

let it_save = it;
it = function(str, fn, to){
  try{
    it_save(str, fn, to);
  }catch(e){
    fail(e);
  }
};

I don't want to do this in every spec file in the beforeAll function. I tried putting this code in onPrepare config option but that throws an error. Is there any way I could achieve this in one place?

Also is there any other way I can fail fast as soon as a error is thrown inside an it? Right now even if an error is thrown the it function runs for the specified defaultTimeoutInterval.

How do I test that forEach is calling savePost three times?

I am learning how to write tests in JavaScript and I have this code here:

function handlePosts() {
    var posts = [
      { id: 23, title: 'Me Gusta JS' },
      { id: 52, title: 'Ciudad Código' },
      { id: 105, title: 'Programar Ya' }
    ];

    for (var i = 0; i < posts.length; i++) {
      savePost(posts[i]);
    }
}

that calls savePost three times, but I am wanting to ensure that when I or someone else utilizes, specifically the forEach helper method, that one of my tests looks for the forEach actually calling savePost three times.

I already developed a test to check that the forEach exists, in other words its being used as opposed to some other array helper method, but not sure how to test that its doing what it should be doing.

describe('forEach', function() {
    it('forEach method exists', () => {
        expect(forEach).toBeDefined();
    });

    it('forEach is calling savePost three times', () => {

    });
});

If anyone could walk me through this, not just looking for the answer, looking to learn how to think about this.

I imagine something like expect(savePost.length).toEqual(3);, but I am not sure.

Cypress - Add custom header for all XHR requests

I notice that X-CSRFToken header is getting removed between tests, for all the XHR requests that triggered from application under test. I'm not sure to preserve this header, as I'm already preserving the Cookies through Cypress.Cookies.preserveOnce('sessionid', 'csrftoken')

Hence, I thought of appending the custom header X-CSRFToken to all the XHR requests from the application. Here is the script I used, where I'm fetching the csrftoken from cookies and setting to custom header.

cy.server({
   onAnyRequest: function(route, proxy) {
        proxy.xhr.setRequestHeader('X-CSRFToken', cy.getCookie('csrftoken'));
   }
})

Here, I'm getting the below error,

Argument of type '{ onAnyRequest: (route: any, proxy: any) => void; }' is not assignable to parameter of type 'Partial<ServerOptions>'.
  Object literal may only specify known properties, and 'onAnyRequest' does not exist in type 'Partial<ServerOptions>'.

I'm expecting any working solution to this approach or a better solution.

Express API file uploads error: ECONNABORTED

I've got an API built in Express, which I'm testing with Jest. The API is working just fine when I test with Postman, but when I run my test suite I usually get an ECONNABORTED error on my file uploads using .attach(). (Occasionally, it works just fine.) I'm using a suite of middleware to download an array of images referenced by URL, followed by any images passed to the endpoint via form upload. After the images are saved, I'm using a third piece of middleware to resize the images and save them in a subdirectory. Since the error only happens in Jest, it seems like that's where the error would lie, but I'm also not positive I'm handling errors with Multer correctly.

// endpoint.js

const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    // Check for product's existence
    if (product) {
      // Make the directory if necessary
      cb(null, /* location */)
    } else {
      cb(404, null)
    }
  },
  filename: async (req, file, cb) => {
    cb(
      null, /* location */}`
    )
  }
})

const upload = multer({ storage }).array("files")

router.post(
  "/:id",
  async (req, res, next) => {
    // Download images from URLs if provided
    next()
  },
  (req, res, next) => {
    upload(req, res, err => {
      // Handle errors (e.g. return res.status(404).json({ message: "Product not found" })
    })
    next()
  },
  async (req, res) => {
    // resize and save to subdirectory
  }
)

// endpoint.test.js

describe("/endpoint", () => {
  describe("POST", () => {
    it("saves uploaded images to the server", async () => {
      const response = await request(app)
        .post(`/endpoint/${id}`)
        .attach("files", "assets/img-test-1.jpg")
        .attach("files", "assets/img-test-2.jpg")
        .set("Content-Type", "multipart/form-data")

      expect(response.status).toEqual(201)
    }, 30000)

  ...

})

How can I specify source files for Cabal/Stack package with more control than just hs-source-dirs/source-dirs?

I have a Haskell project that is built using Stack (therefore Cabal). Right now I have src/ directory and tests/ directory, however I would like to mix tests together with the source files, which means everything would go to src/ directory.

For that, I would need to define my tests build-info source files to be files in src/ that have .test.hs extension. However, it seems that only choice for defining source files is source-dirs in stack or hs-source-dirs in cabal, meaning that I have to put src as source-dirs, which seems wrong because it is also capturing the normal source files then.

This is what part of my package.yaml:

tests:
  myapp-test:
    main:                Main.hs
    source-dirs:         test
    ...

While I would like it to be smth like:

tests:
  myapp-test:
    main:                Main.hs
    source-files:         src/**/*.test.hs
    ...

Is there any option like that, like source-files, or any other way to do this? Thanks!

Using Postman only for mocking, in addition to Katalon automation

I'm currently working on Katalon Studio automated testing, and I have to setup a Mock Server for this testing purposes.

So, I wondered if its ok to use Postman only for mocks, and may be a silly question but I don't know anything about mocking right now. I saw that there are like libraries of mocking, but I see that Postman makes it easier, with a nice graphic interface, and since I don't have a large technical background I want to take the simplest path to achieve this mock server.

Also I saw that with SoapUI you can make mocks too. Wouldn't that limitate the mocking only to SOAP?

As you see I don't know much haha, so any help is welcomed.

Thanks beforehand

ASP.NET Core test method with DisableRequestSizeLimit

I have an ASP.NET Core project, with this method:

public async Task<ActionResult<ResultDto>> StartReadFiles(
    [ModelBinder(typeof(JsonModelBinder))] RequestDto request,
    IFormFile file1,
    IFormFile file2
)

After I pushed the method, the performance test failed because he sends very large files in the request.

So I added DisableRequestSizeLimit to the method:

[DisableRequestSizeLimit]
public async Task<ActionResult<ResultDto>> StartReadFiles(
    [ModelBinder(typeof(JsonModelBinder))] RequestDto request,
    IFormFile file1,
    IFormFile file2
)

And now, I want to write a test for this bug.

How can I fake the request with a very big body?

Generating test reports with Ant and TestNG with selenium webdriver

I using file "build.xml" for generating the reports for the tests but when i compile my file on cmd then it shows build successful but when i run my file using "ant run" command on cmd then it shows an error "no suites classes methods or jar file was specified" Please check my code: I used selenium webdriver with java and also link all the required jar files to the build.xml file

    <?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE project [
]>

<project name="TestNG Module" default="usage" basedir=".">  

<!-- ========== Initialize Properties =================================== -->
    <property environment="env"/>

   <property name="test.dest" value="${ws.home}/build"/>
    <property name="test.src" value="${ws.home}/src"/>
    <property name="ng.result" value="test-output"/>
    <property name="ws.jars" value="E:\New folder\TestNG"/>



    <target name="setClassPath" unless="test.classpath">
        <path id="classpath_jars">
            <fileset dir="${ws.jars}" includes="*.jar"/>
        </path>
        <pathconvert pathsep=":" 
            property="test.classpath" 
            refid="classpath_jars"/>
    </target>


<target name="run" depends="compile">
        <testng classpath="${test.classpath}:${test.dest}" suitename="suite1">  
            <xmlfileset dir="${ws.home}" includes="testng.xml"/>
        </testng>
     </target>

    <target name="init" depends="setClassPath">
        <tstamp>
            <format property="start.time" pattern="MM/dd/yyyy hh:mm aa" />
        </tstamp>
        <condition property="ANT" 
            value="${env.ANT_HOME}/bin/ant.bat" 
            else="${env.ANT_HOME}/bin/ant">
                    <os family="windows" />
        </condition>
        <taskdef resource="testngtask" classpath="testng.jar"/>
       <taskdef name="testng" classname="org.testng.TestNGAntTask">
<classpath>
<pathelement location="E:\New folder\TestNG jars\testng-6.8.5.jar"/>
</classpath>
</taskdef>
    </target>

    <!-- all -->
    <target name="all">
    </target>

    <!-- clean -->
    <target name="clean">
        <delete dir="${test.dest}"/>
    </target>

    <!-- compile -->
    <target name="compile" depends="init, clean" > 
        <delete includeemptydirs="true" quiet="true">
            <fileset dir="${test.dest}" includes="**/*"/>
        </delete>
        <echo message="making directory..."/>
        <mkdir dir="${test.dest}"/>
        <echo message="classpath------: ${test.classpath}"/>
        <echo message="compiling..."/>
        <javac 
            debug="true" 
            destdir="${test.dest}" 
            srcdir="${test.src}" 
            target="1.5" 
            classpath="${test.classpath}"
        >
        </javac>
      </target>

    <!-- build -->
    <target name="build" depends="init">
    </target>

    <!-- run -->



    <target name="usage">
        <echo>
            ant run will execute the test
        </echo>
    </target>

    <path id="test.c">
            <fileset dir="${ws.jars}" includes="*.jar"/>
    </path>

      <target name="makexsltreports">
            <mkdir dir="${ws.home}/XSLT_Reports/output"/>

            <xslt in="${ng.result}/testng-results.xml" style="src/xslt/testng-results.xsl"
                  out="${ws.home}/XSLT_Reports/output/index.html" classpathref="test.c" processor="SaxonLiaison">
                <param name="testNgXslt.outputDir" expression="${ws.home}/XSLT_Reports/output/"/>
                <param name="testNgXslt.showRuntimeTotals" expression="true"/>
            </xslt>
        </target>



</project>

How to fabricate a turnContext for testing Microsoft Botbuilder SDK?

IDE: Visual Studio 2017 SDK: Botbuilder V4 Emulator: Bot-Framework Emulator V4 Language: Node.js v11

Hi all. I am making test cases for some largely static functions/methods of my bot code. However, I will later need to test more advanced functionality of my bot to test for specific behavior. Does anyone know how to fabricate some parts of the turnContext?

For example, I am fabricating my own right now by manually creating a simulated turnContext JSON in the following way:

turnContext {
activity: {
    text: "custom test text",
    channelID: "custom ID",
    conversation: {
        id: "custom ID" } } }

The problem is that this fabricated context doesn't actually have the inhereted methods like turnContext.sendActivity('custom message');. So my tests will be limited to only the most basic functionality of the bot that won't actually guarantee the entire behavior is performing as designed.

Pytest-django migration error with --nomigrations option

I am trying to get pytest-django (3.4.8) working with my Django (2.1.1) project. I have --nomigrations set as per docs, because I don't want migrations for tests. However, when I run the test I see a migration error:

django.db.utils.ProgrammingError: relation "contact_contact" does not exist

This error does not occur when I run the app, so I assume it is something to do with my test setup. My pytest.ini:

[pytest]
DJANGO_SETTINGS_MODULE=my_app.settings.test
addopts = --capture=no --cov=. --cov-report=html --nomigrations
testpaths = tests

I'm using postgres, django-tenants, and the app and tests run inside of Docker. I'm not sure what actual code besides pytest.ini would be relevant to this issue, but I can provide more configs/code.

How can I mock an http error response in dart?

So I'm doing some unit tests for my http provider.

In one of my tests I want to verify that when I do a POST call and I get an error response with status 409 I do then a call to PATCH and everything works.

This is my code

  Future<IdentityResponse> _createUser(dynamic body) {
    return http
        .post(api, body: json.encode(body))
        .catchError((err) {
      return _isStatusCode(err, 409) ? _patchUser(body) : throw (err);
    });
  }

I'm using mockito, and tried first returning a Response like this:

when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
        .thenAnswer((_) async => Response("user exists", 409);

And it works... kind of. I catch the error, but then I can't get the status code, I get only the message 'user exists'

If I change to the structure that the backend returns, which is {"error": { "code": 409 }} and I do this:

when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
        .thenAnswer((_) async => Response(json.encode(fakeErrorResponse), 409);

Then my catch does not work anymore (??)

I tried then to return an error instead of a response, like this:

when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
    .thenAnswer((_) => Future.error(fakeErrorResponse));

Now my catch works again, but the error I get is an _ImmutableMap and I see no easy way to retrieve my data from there.

How can I mock an http error that returns the body that I want and not a simple String?

Thanks

How to run karma tests in Angular when stylus stylesheets are used?

I'm not sure whether I constructed the question title right. I want to run tests for my Angular 7 application by using ng test. In one of my component I have a Stylus stylesheet used:

@Component({
  selector: 'app-root',
  template: ``,
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['../../../../src/app/globalNg1Styles.styl']
})

It works fine when I serve the application but I have this error when I try to run the tests:

ERROR in (...)/src/app/globalNg1Styles.styl
Module build failed (from (...)node_modules/stylus-loader/index.js):
TypeError: Cannot read property 'stylus' of undefined at Object.module.exports ((...)node_modules/stylus-loader/index.js:29:33)
 @ ./src/app/catalog.component.ts 18:21-72
 @ ./src/app/catalog.component.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

I don't get what's wrong and how can I solve the problem.

Run build and tests in dockerfile vs on CI?

the fastest way to run tests on CI is ./gradlew test or ./gradle build. it will download all the necessary dependencies (which can be somehow cached on CI), run tests and produce artifact (jar file)

i also want to build a docker image. some of the options i considered:

  • build docker image on CI and assume that artifact is already there. it's the fastest way but ties the building process to CI. it can't be just build manually with 1 command (docker build)

  • run tests as part of docker build. on CI it takes more time before i get info about failing test (as it has to download image, dependencies etc). but it allows to easily build the docker locally (probably rarely used functionality but useful for local docker-compose for tests)

  • parameterized build to disable / enable tests by default

what's the standard way of handling those requirements? any best practices?

Print current DOM element

I'm trying to select an element based on a sibling element, similar to this post. However, I get an error The specified selector does not match any element in the DOM tree. which means that testcafe didn't find my element.

To help debug, it would be good if I could print the DOM element currently being read by Selector().

Using console.log(Selector('element')) prints out the object. Is there a way to output the current DOM element?

compiling cmocka with the xc8 compiler from microchip howto?

Good afternoon devs,

When I checkout the latest cmocka version and try to compile cmocka with the xc8 compiler version 1.41 the code wont compile syntaxis error.

It isnt recommend or the solution to change this cmocka source, because in the future when a new cmocka version is out. its not nice to have to change that file again.

So the requirement is a solution without changing the cmocka code.

Or is this totally wrong thinking, it would be nice if you devs can push me in a direction for this.

Update:

include\cmocka.h: 256: (163) unexpected text in control line ignored (warning)
include\cmocka.h: 1645: (112) #define syntax error (error)
include\cmocka.h: 1645: (163) unexpected text in control line ignored (warning)

the messages, but when I removed this code, it would error out on like 500 more errors.

MVC 5 Wanting to testing with SpecFlow

I want to build a mini Asp.net MVC 5 application which only has a login page. I need to use BDD so I decided to use Specflow but how can I write my given,when,then test methods that will check when I enter username and password is valid or not.

In short, I want to use BDD specflow testing when I enter login information(username,password).I don't know what to write in controller and how to take data from view to give that in specflow methods, can you help me? Do I need to use Assert for example in methods, or given,when,then methods will be in controller ?

How to add negative assertions like not.toHaveText in Detox?

I need to set negation for some text content and tried the code below but as it isn't stated in the docs I expected it to fail and it sure did, so I would like to know how could I possibly achieve negation in this case.

await expect(element(by.id('myElemId'))).not.toHaveText('some text')

Testing the LSTM in Tensorflow

My network has Stacked LSTM->FC Layer. If i have to pass the input for testing, Can I just pass it to last FC layer, so that graph will connect fetching corresponding inputs for each layer or should I have to rebuild the graph?

I have constructed my code something like below:

with tf.Session() as sess:    

    saver = tf.train.import_meta_graph(r'my_model.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    graph = tf.get_default_graph()
    w1 = graph.get_tensor_by_name("batch_x:0") 
    w2 = graph.get_tensor_by_name("batch_y:0") 
    operation = graph.get_tensor_by_name("fully_connected/Relu:0")
    output=sess.run(operation,{w1:input})

I'm expecting one hot vector and I am not getting, Please let me know how to do it. I have read many posts I am getting confused with every other post.

Am new to to Protractor testing, Could you please advise me how to write script for login webpage and go to next page

Am new to Protractor testing, am writing the script for login page and need to go to next page. Could you please advise me on this how to proceed this

Cypress cutting down "X-CSRFToken" header

Noticed that Cypress test runner is cutting out X-CSRFToken from the request header, which causes the request to return 403 Forbidden. Here is the screenshot of headers from manual run and Cypress test run,

Screenshot taken while navigating in Chrome browser: enter image description here

Screenshot taken while running Cypress test: enter image description here

To confirm this, I replayed the request through curl attaching the X-CSRFToken. It worked fine then. How could I handle this while running Cypress tests?

seekbar automation in android app using robot framwork

I want to automate seek bar using robot framework how to set value and get max and min value of seekbar?

${value}    Get Element Attribute       ${SetPointValue_set}        minHeight
Log To Console     \n\n\r Value2 --> ${value}

not able to acess seek bar method and attribute.

Measure the load time of multiple web elements in Selenium

I would like to measure load times of multiple parts of a spinner element. HTML looks like this:

<div id="loading">
    <div id="spinner">
        <div class="spinner-icon"></div>
    </div>
    <p class="spinner-text">Please wait</p>
</div>

I'm interested which of the elements is loaded/displayed first? The icon? Text?

I was thinking of something like this:

Date t1 = new Date();
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("#loading")));
Date t2 = new Date();
long duration = t2.getTime() - t1.getTime();

But, can I use intertwined waits? Can I do this in a single script?

Why this function does not called in Jest tests?

I'm trying to test a function in React using Jest. It's working in production and development environments perfectly but Jest is saying it doesn't called. As a consequence the state in test returns 0 data length while it should be 1!

This is the function:

  addStory(story) {
const idToken = this.state.user.idToken
if (!idToken) return
const storyProps = {
  Title: story.title,
  Body: story.body,
  UserEntityKey: story.userEntityKey,
  AuthorName: this.state.user.displayName,
  AuthorPicture: this.state.user.photoURL
}

// Axios call should return Promise result for proper testing.
const promise = Axios.post(apiUrl, storyProps, { headers: { 'Authorization': idToken } })
promise.then(res => res.data)
promise.then(newStory => {
  newStory.data.AuthorName = this.state.user.displayName
  newStory.data.AuthorPicture = this.state.user.photoURL
  this.setState(({ data }) => {
    data.unshift(newStory.data)
    return { data: data, isAddStoryVisible: false }
  })
})
promise.catch((error) => {
  console.error(error)
})
return promise

};

and this is the test:

test('Story adds based on mocked backend response', async () => {
  MockAxios.post.mockImplementationOnce(() =>
    Promise.resolve(story)
  )

  const storyApp = shallow(<StoryApp />);

  // Test without idToken
  // Axios call should return Promise result.
  await storyApp.instance().addStory(story)
  expect(storyApp.state().data.length).toEqual(0)

  storyApp.setState((prev) => {
    prev.user = {
      idToken: "asdf",
      displayName: "Test name",
      photoURL: "Test photo"
    }
    return prev
  })

  // Test with idToken
  await storyApp.instance().addStory(story)
  expect(storyApp.state().data.length).toEqual(1)
})

and finally here is the test output:

  ● Story adds based on mocked backend response

expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  0

  92 |   // Test with idToken
  93 |   await storyApp.instance().addStory(story)
> 94 |   expect(storyApp.state().data.length).toEqual(1)
     |                                        ^
  95 | })
  96 | 
  97 | test('Story deletes based on mocked backend response', async () => {

  at Object.toEqual (__tests__/App.test.js:94:40)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:288:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
  at asyncGeneratorStep (__tests__/App.test.js:25:103)
  at _next (__tests__/App.test.js:27:194)

Thank you :-)

Creating an instance of UserManager

I'm very new to the concept of mocking and I struggle with injecting/mocking an UserManager<T> to my tests

I need to use await _userManager.CreateAsync(user, password);

I've found this one

public static UserManager<TUser> TestUserManager<TUser>(IUserStore<TUser> store = null) where TUser : class
{
    store = store ?? new Mock<IUserStore<TUser>>().Object;
    var options = new Mock<IOptions<IdentityOptions>>();
    var idOptions = new IdentityOptions();
    idOptions.Lockout.AllowedForNewUsers = false;
    options.Setup(o => o.Value).Returns(idOptions);
    var userValidators = new List<IUserValidator<TUser>>();
    var validator = new Mock<IUserValidator<TUser>>();
    userValidators.Add(validator.Object);
    var pwdValidators = new List<PasswordValidator<TUser>>();
    pwdValidators.Add(new PasswordValidator<TUser>());
    var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher<TUser>(),
        userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
        new IdentityErrorDescriber(), null,
        new Mock<ILogger<UserManager<TUser>>>().Object);
    validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
        .Returns(Task.FromResult(IdentityResult.Success)).Verifiable();

    return userManager;
}

But this throws

System.NotSupportedException : Store does not implement IUserPasswordStore.

How can I create an working UserManager<T> instance in tests?

I'm using Xunit

Autotests with webpack-dev-server

I'm quite confused with topic.

I develop a some kind of lazy module assembler using webpack-dev-server. It finally works but sometimes we need more assurance. That's why I need some tests. The task is to make them a kind of autotests.

For now the code of server start looks like this (I omit excessive params).

import webpack from "webpack";
import webpackConfig from "../webpack.config.js";
import webpackCompileConfig from "../webpack-compiler.config.mjs";
import WebpackDevServer from "webpack-dev-server";

webpack(webpackConfig(mode, dirname, masterPath)).run(function(err) {
  if (err) throw err;

  const compileOpt = {
    // pack of compiler options
  };
  const compiler = webpack(webpackCompileConfig(compileOpt));

  const server = new WebpackDevServer(compiler, {
    // pack of server options
  });

  server.listen(port, "0.0.0.0", err => {
    if (err) throw err;
    console.log(`Starting root server on 0.0.0.0:${port}`);
  });
});

It starts and works properly: gets some file requests, bundles necessary modules with webpack and sends them to requester.
Simple test I want to start with are to check are there files after assembling or not.

Supposed logic is:

  • Run some command inside this project, e.g. npm run test
  • It starts server and sends a pack of requests with different logic I want to test (parallel, simultaneous requests etc.)
  • It tests file existence and send me results in console or smth. of that sort

The problem is my very little expirience in any kind of testing so I'll appreciate your help.

===
The way I use it now (spoiler: manually)

The only thing the Internet helps me about.

  • Server starts as usual
  • There is another fully off-site test module (code below)
  • Run mocha
  • See listed test results

test-server.js

var chai = require("chai");
var chaiHttp = require("chai-http");

const should = chai.should();
chai.use(chaiHttp);

describe("Test file existence", function() {
  it("units", done => {
    chai
      .request("http://localhost:9000")
      .get("/units/awesome-project/index.js")
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
  });
  // another 'it()'s to test other files
});

Yes, it works. But I want more automatisation. Just

  • Run server
  • Send requests
  • Get test results

I'm ready for dialog.

mercredi 27 février 2019

Testing handle change function in React using Enzyme and Jest

My react component contains this code

 handleChange = e => {
    this.setState({
      num: e.target.value
    });
  };

  render() {
    return (
      <div>
        <h2>Delete cat :(</h2>
        <input
          onChange={this.handleChange}
          type="number"
          placeholder="enter id here"
        />
        <button id="deleteBtn" onClick={this.deleteOne}>
          Delete
        </button>
      </div>
    );
  }
}

As you can see, the handleChange function fires when the input changes and will update state from there.

How can I test this using Enzyme? I've tried

 it("Updates the state", () => {
     const wrapper = shallow(
       <Provider store={store}>
         <DeleteOne />
       </Provider>
     );
     const input = wrapper.find("input");

     input.simulate("change", { target: { num: 2} });

     expect(wrapper.state().num).toEqual(2);
   });
});

I had to attempt to wrap it in store because I'm using Redux and exporting a connected component. I've been Googling the last hour and trying all sorts but weren't able to get this test passing. Please send help :) cheers

PS: I've tested the button click no worries as it just runs a function (no state update).

How to get Android context in Kotlin multiplatform Android test?

I have the following build.gradle file:

plugins {
    id 'com.android.library'
    id 'kotlin-multiplatform' version '1.3.20'
    id "org.jetbrains.kotlin.kapt" version "1.3.20"
}

group 'com.company.project'
version '0.8'

apply plugin: 'maven-publish'

android {
    compileSdkVersion 27
    defaultConfig {
        minSdkVersion 15
    }
    buildTypes {
        release {
            minifyEnabled false
        }
    }
}

kotlin {
    jvm()
    wasm32('wasm')
    android()

    sourceSets {
        commonMain {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
                implementation "org.jetbrains.kotlin:kotlin-reflect"
            }
        }
        commonTest {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-test-common'
                implementation 'org.jetbrains.kotlin:kotlin-test-annotations-common'
            }
        }
        commonJvmMain {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
            }
            dependencies {
                implementation 'net.sf.trove4j:trove4j:3.0.3'

            }
        }
        jvmMain {
            dependsOn commonJvmMain
        }
        jvmTest {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-test'
                implementation 'org.jetbrains.kotlin:kotlin-test-junit'
            }
        }
        androidMain {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
                implementation "android.arch.persistence.room:runtime:1.0.0"
            }
        }
        androidTest {
            dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-test'
                implementation 'org.jetbrains.kotlin:kotlin-test-junit'

                implementation "android.arch.persistence.room:runtime:1.0.0"
            }
        }
    }
}

dependencies {
    androidTestImplementation 'junit:junit:4.12'
    androidTestImplementation 'org.jetbrains.kotlin:kotlin-test'
    androidTestImplementation 'org.jetbrains.kotlin:kotlin-test-junit'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    kapt "android.arch.persistence.room:compiler:1.0.0"
}

In src/androidTest/kotlin/.. i have the following test:

package com.company.project.test

import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.test.*

@RunWith(JUnit4::class)
class DbDaoTest {

    private val map = memEffMapOf<String, String>()

    @BeforeTest
    fun setUp() {
        val context = InstrumentationRegistry.getTargetContext() // Crash here
        val db = Room
            .inMemoryDatabaseBuilder(context, MapDatabase::class.java)
            .build()
        MapDaoHolder.dao = db.mapDao()
    }

    @Test
    fun testAdd() {
        ...
    }
}


It crashes in setUp():

java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.

    at android.support.test.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:44)
    at android.support.test.InstrumentationRegistry.getTargetContext(InstrumentationRegistry.java:82)
    at com.company.project.test.DbDaoTest.setUp(DbMapFactoryTest.kt:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

What should i do? I've looked into JetBrains mpp android test example, but it does not use android context, so does not have this exception.

PS. I'm able to run common tests without any issues.

Is Allure report supported by Travis?

I couldn't find any information about integration of Allure report with Travis. Is it possible to generate Allure report on Travis?

How to set the browser language using Selenium for Safari, IE and Edge browser?

I understand you can set the browser language using browser options. For instance-

On Firefox-

FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("intl.accept_languages", "en-gb");
caps.setCapability(FirefoxDriver.PROFILE,fp);

On Chrome-

ChromeOptions options = new ChromeOptions();
options.addArguments("--lang=en-gb");
caps.setCapability(ChromeOptions.CAPABILITY,options);

How can I achieve the same for Safari, IE and Edge browser using Selenium?

I could not find official documentation around this!

Cypress fixtures usage in TypeScript

I have used Cypress with Javascript specs and recently switched to Typescript. While using Fixtures, I had the below approach working in Javascript; but, with Typescript I face some difficulty.

Fixture JSON file: I have my fixture file in /cypress/fixtures/sql_queries.json

{
    "query_1": "SELECT * FROM TABLE_1",
    "query_2": "SELECT * FROM TABLE_2",
}

Before:

   before('Load data to fixture', () => {
        cy.fixture('sql_queries')
            .as('sqlQueries')
   })

Test spec: I'm consuming the loaded fixture file in below sample test,

   it('Test something', () => {
        cy.get('@sqlQueries')
            .then((queries) => {
                cy.log(queries.query_1)
            })
    })

Problem: I'm getting the error as Property 'query_1' does not exist on type 'JQuery<HTMLElement>

Any help would be appreciated.

grep result of npm test in bash conditional

I need to grep the result of an

npm test

from my bash conditional.

So I can stop my CI/CD environment

there is a suggestion to use grep like:

VALID="$(npm test | grep -o 'failing')"

but when I do that, just to try what actually is in the pipeline for "npm test"

VALID="$(npm test)"

What I see is:

echo "$VALID"

> MyApp@0.0.1 test /Users/NE/ts/project
> jest

SO, how will that work? how can I really grep the result of the npm test?

thanks!

Run protractor in localhost server during countinuous integration

I have been studying protractor and I have wrote some tests in with our production web app. Now I want to integrate this tests on our continuous integration. If the tests fail it should not continue to continuous release.

To achieve this I planned to run the same test in local server with the target version that is going to production. My project is coded in angularjs. My package.json file has a script to start a local server and other to test but I'm not being able to wait the server complete to up before running my tests.

Te question is: How can I run my tests in localhost web server?

My selenium config file

exports.config = {
    framework: 'jasmine',
    seleniumAdress: 'http://localhost:4444/wd/hub',
    suites: {
        fluxos: './specs/fluxos/spec.js',
        validacoes: './specs/validacoes/spec.js'
    },
    capabilities: {
        browserName: 'chrome'
    },
}

My package.json

{
  "scripts": {
    "build": "gulp build:dev",
    "build:hmg": "gulp build:hmg",
    "build:hmgi": "gulp build:hmgInterno",
    "build:prod": "gulp build:prod",
    "coverage": "gulp test:build",
    "lint": "./node_modules/.bin/eslint **/*.js",
    "precommit": "npm run lint",
    "prepush": "npm run coverage",
    "start": "gulp serve:dev",
    "start:hmg": "gulp serve:hmg",
    "start:hmgi": "gulp serve:hmgInterno",
    "start:prod": "gulp serve:prod",
    "test": "gulp test",
    "integration:validacoes": "gulp serve:prod && protractor ./tests/integration/conf.js --suite validacoes",
    "integration:fluxos": "gulp serve:prod && protractor ./tests/integration/conf.js --suite fluxos"
  },
  "dependencies": {
    "@uirouter/angularjs": "^1.0.15",
    "@uirouter/core": "^5.0.17",
    "angular": "^1.6.8",
    "angular-cookies": "^1.6.8",
    "angular-format-masks": "^1.0.2",
    "angular-i18n": "^1.6.8",
    "angular-input-masks": "^4.1.0",
    "angular-sanitize": "^1.6.8",
    "angular-spinner": "^1.0.1",
    "angular-touch": "^1.6.8",
    "angulartics": "^1.6.0",
    "angulartics-google-tag-manager": "0.0.1",
    "ng-accessibility-bar": "^1.2.3",
    "spin.js": "^2.3.2"
  },
  "devDependencies": {
    "angular-mocks": "^1.6.10",
    "autoprefixer": "^8.1.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "browser-sync": "^2.23.7",
    "browser-sync-spa": "^1.0.3",
    "del": "^2.2.2",
    "eslint": "^3.12.2",
    "eslint-config-airbnb": "^13.0.0",
    "eslint-config-angular": "^0.5.0",
    "eslint-plugin-angular": "^1.6.1",
    "eslint-plugin-import": "^2.11.0",
    "eslint-plugin-jsx-a11y": "^2.0.0",
    "eslint-plugin-react": "^6.8.0",
    "gulp": "^3.9.1",
    "gulp-cachebust": "0.0.6",
    "gulp-clean-css": "^3.9.3",
    "gulp-eslint": "^4.0.2",
    "gulp-group-css-media-queries": "^1.2.2",
    "gulp-gzip": "^1.4.2",
    "gulp-htmlmin": "^3.0.0",
    "gulp-if": "^2.0.1",
    "gulp-imagemin": "^3.4.0",
    "gulp-ng-annotate": "^2.1.0",
    "gulp-ng-constant": "^2.0.0-3",
    "gulp-postcss": "^7.0.1",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^3.2.1",
    "gulp-sourcemaps": "^2.6.4",
    "gulp-uglify": "^1.5.4",
    "gulp-uglify-es": "^1.0.4",
    "gulp-uncss": "^1.0.6",
    "gulp-useref": "^3.1.5",
    "husky": "^0.12.0",
    "imagemin-gifsicle": "^5.2.0",
    "imagemin-jpegtran": "^5.0.2",
    "imagemin-optipng": "^5.2.1",
    "imagemin-svgo": "^5.2.4",
    "jasmine": "^2.99.0",
    "jasmine-core": "^2.99.1",
    "karma": "^1.7.1",
    "karma-babel-preprocessor": "^6.0.1",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage": "^1.1.1",
    "karma-jasmine": "^1.1.1",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-spec-reporter": "0.0.26",
    "karma-threshold-reporter": "^0.1.15",
    "postcss-pxtorem": "^4.0.1",
    "protractor": "^5.4.2",
    "protractor-helper": "^3.7.0",
    "run-sequence": "^1.2.2"
  }
}

Google Analytics Mock Testing accounts with eCommerce data

I am a tester looking for a solution for testing our software integration with Google Analytics. I am testing a software that utilises the API routes provided from Google Analytics, I need access to a Google Analytic account with eCommerce data.

Our company does not have eCommerce data, as we are not a company about selling goods to customers. So I am looking for some advice on what people have done in order to test certain API routes from Google Analytics, when they don't have access to it with a real account.

I have tried using Google's own mock account for testing, but it doesn't grant access for integrations.

So if anyone has a solution or ideas for how I can go about this, would be great :).

Get notification after project deployed on AWS Beanstalk

I have a project(a simple RESTful service) deployed on AWS beanstalk. I would like to run a few test cases to do the sanity check after the project is up. It seems you could only get an email from SNS but I need an HTTP call to invoke my test instance.

I appreciate your help.

Test static content with MockMVC in Spring Boot with Slice

I'm trying to figure out a way to test with MockMVC the serving of content using a WebSlice that only autoconfigs org.springframework.web.servlet.resource.ResourceHttpRequestHandler (and not controllers)

i've tried something like this:

@RunWith(SpringRunner.class)
@WebMvcTest(
    controllers = {}
)
public class StaticAssetsMVCTest {

but {} is the default and it looks for all controllers. Is there a way to exclude all controllers but keep the other basic spring-web things my app has so that i can test just the static assets slices?

Why Steps with parenthesis doesn't match in Groovy/Java Code when using Katalon/Cucumber?

Setting up:

The feature file does not allow to modify and it shows below.

Feature: create news
  Scenario: company check the news
    Given Java has a news with number (100)

Step definition in Katalon / Groovy Code / Cucumber :

@Given("(.*) has a news with number ((\\d+))")
def check_user__with_news_number(String name, String num){

}

I had tried to use (something) but the katalon does not recognized it

error: Step Java has a news with number (100) does not have a matching glue code

Katalon Studio Version: 6.0.4 Build: 1

Groovy Compiler version 2.4.7

Java 8

Also: I had checked those issues already but the problem still is there

https://github.com/cucumber/cucumber/issues/107

https://docs.cucumber.io/cucumber/cucumber-expressions/#escaping

https://github.com/cucumber/cucumber/issues/103

How to run queue task during local testing with Java Appengine

I'm having a hard time finding what I'm looking for in the documentation (under "Writing task queue tests").

What I'm trying to do is probably beyond a "unit" test. For my test, I call a function that runs an update to my local database and then queues a task to build out and send an email. I need to be able to actually fire my queue task to ensure the task itself functions properly based on the data it pulls from the database.

I am failing to understand from the documentation how to actually ensure my task is executed. Here is my config so far:

private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalTaskQueueTestConfig()
    .setQueueXmlPath("/full/path/to/queue.xml")
    .setDisableAutoTaskExecution(false));

Elsewhere, I add to the queue:

Queue someQueue = QueueFactory.getQueue(SOME_QUEUE.getQueueName());
someQueue.add(TaskOptions.Builder.withUrl("/some-url")
    .param("someParamName", "someParamValue"));

I don't get any errors, it's just not running my task. Is the issue that I'm running withUrl() and need to set some path for my web.xml? The queued task hits a Servlet.

Enable sinon fakeServer logs

I'm running several tests where I'm mocking http calls using sinon fake server:

import sinon from 'sinon';
...
const fakeServer = sinon.fakeServer.create();
fakeServer.respondWith('POST', '/myapp/myendpoint/pathparam', [201, { 'Content-Type': 'application/json' }, myPayload]);
...

However the fake server is returning a not found error: [404, { }, (empty string)].

I cannot figure out what's going wrong.

Is there any way to activate some kind of logs that tells me what is going on?

After going over sinon's documentation, I cannot find anything about logs or debug flags.

when I test the app.js I have a problem that appears

when I test App.js I have the following error that appears:

TypeError: Cannot read property 'createStackNavigator' of undefined

      24 |             borderBottomWidth:0,
      25 |         },
    > 26 |         headerTintColor: '#294c95',
         |                                                  ^
      27 |         headerTitleStyle: {
      28 |             fontWeight: 'bold',
      29 |             color:'white',

the file that indicates, it is HomeNavigation.js. On the other hand the line that indicates is correct and in this file the code is correct

here is my test

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

global.fetch = jest.fn(() => new Promise(resolve => resolve()));
jest.mock('react-native-gesture-handler', () => {});
jest.mock('react-navigation-stack', () => { BaseButton: {} });
//jest.mock('react-navigation', ()=>{}); //if I add or remove this line it doesn't change anything.

describe('App', ()=> {
  it('renders correctly the App component', () => {
    const tree = renderer.create(<App/>).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

  • jest.mock('react-native-gesture-handler', () => {}) this line solves this problem: TypeError: Cannot read property 'State' of undefined

  • jest.mock('react-navigation-stack', () => { BaseButton: {} }); this line solves this problem: TypeError: Cannot read property 'BaseButton' of undefined

HomeNavigation.js

import React from "react";
import {createStackNavigator} from "react-navigation";
import {Screen1Screen} from "../Screen"; //whatever name
import {Icon} from "react-native-elements";
import {fromRight} from 'react-navigation-transitions';
import {CLR_MENU} from "../assets/styles/colors";

export const HomeNavigation = createStackNavigator({
    Screen1: Screen1Screen // whatever name // this part is correct
},{
    cardStyle: {
        backgroundColor: 'black',
        opacity: 1,
    },
    defaultNavigationOptions: (navigation) =>({
        headerStyle: {
            backgroundColor: [CLR_MENU],
            borderBottomWidth:0,
        },
        headerTintColor: '#294c95', // the error point on this line
        headerTitleStyle: {
            fontWeight: 'bold',
            color:'white',
        },
        headerRight:
            <Icon
                name = "menu"
                size = {24}
                color = "white"
                onPress={_=>navigation.navigation.openDrawer()}
                containerStyle=
                underlayColor={CLR_MENU}
            />,
    }),
    transitionConfig: () => fromRight(),
});

Capybara test reverse proxied domains

I'm currently working on a rails application which has an interesting setup.

We have two applications running on heroku. One is a basic app which works as a reverse proxy, it has multiple domains attached to it and it reverse proxies to our main application which is a rails application ( this application does a look up based on the host then for the routing ).

The reason for this setup is to allow custom domains pointing to "shop pages" on the main application, these shop pages then point back to the original domain for a checkout.

Maybe an example will better explain it, 2 domains: seller.com platform.com

platform.com represents the app host for the main application, seller.com is a domain routed through the reverse proxy. On seller.com you choose your products and then ultimately you check out on platform.com

We're struggling to find a way to test this end to end flow in our main application using capybara given the multiple domains, is there any way to handle this by spoofing the reverse proxy or just using multiple hosts?

Get system date with BadBoy software for testing

I am creating a script for application tests, in order to export it and use it with JMeter.

I would need to get the system date as a variable, at the script level, not the environment, but I can not do it in any way.

Any advice?

Thanks in advance

What data analysis test should I use?

I need a recommendation for a data analysis test I should for the following situation:

I have two independent variables, A and B. In this situation, every A value is linked to a B value. I want to determine if the value of A has an significant affect on the mean of B.

i.e. If A is a small value like 10 and its B value is a large value like 30, I want to determine if A being small has a significant impact on the mean of all B values. I want to see how small an A value needs to be to disregard it. The A value ranges from 1 to 1,000,000 and the B value ranges from -20 to 20.

Any advice? Thank you.

Testcafe - Page object structure and default class

I'm modeling a web page with a lot of items on it. Coming from a Ruby background, I had one class for each, say, large item and its subitems on the page. For instance, a navbar would be its own class:

import { Selector, t } from 'testcafe';

export class NavBar {
  constructor () {
    this.home = Selector('#home')
    this.intro = Selector('#intro')
    ...
  }
}

export class HeaderSection {
  ...
}

Questions:

  1. Do I need a default class? My IDE is complaining, but the test work. I believe, the answer is no, but it's a good practice(?)
  2. What's the recommended way to write a complex page model in JavaScript? I'm leaning to have one page class, say index and then have multiple child classes (Navbar and HeaderSection on my example) that inherit from the index class

Get acting as user's id when testing in Laravel

Laravel 5.7. I have a test like this:

/** @test */
public function do_nothing_test()
{
    $user = factory(User::class)->states('app')->make();
    $this->actingAs($user, 'api');
    $response = $this->postJson('some_endpoint');
}

which calls an endpoint in a controller that tries to get the logged in user:

public function useless_endpoint()
{
    $id = auth()->user()->id;
}

The value of $id is null. How can I get the test to work so that the user's details are available to the controller?

How to create a apex test class for my apex class

It is my first apex class and i don't really know how to implement a proper test class. My goal is to achieve test coverage of 75%.

Here is what i did :

Apex class:

public with sharing class AccountController {

@AuraEnabled
public static List<Account> findAll() {

    User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
        where Id=:userinfo.getUserId() ];

    // Theme4t is theme that is used by mobille app for  android or iphone 
    if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non')
        || (userDetails.UserRole.Name).contains('go')) && UserInfo.getUiTheme() != 'Theme4t'){
       return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
        FROM Account
        WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL 
        LIMIT:22000];

    }else {
       return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
        FROM Account
        WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL 
        LIMIT:5000]; 

    }
}

Apex test class:

@isTest 
public class AccountControllerTest 
{
    static testMethod void testMethod1() 
           {
                          Account acc = new Account();
                          acc.Name='Test';
                          insert acc;

                         User userDetails = new User();
                         userDetails.UserRole.Name='yon';
                         insert userDetails;

                          List<Account> lstAcc = AccountController.findAll();

                         UserRole ur = new UserRole(Name = 'bon');
                         insert ur;
                           List<Account> lstAcc2 =AccountController.findAll();     
    }
}

How to test the then part after promise in jest

I'm working on a React project and I'm using jest to write tests for my code.

This is the code I want to test.

const handleSubmit = (handleSuccess, handleErrors) => {
  signupAPI(user)
    .then(handleSuccess)
    .catch(handleErrors);
};

Here's the test code:

test('should call handleSuccess', () => {
  signupAPI.mockImplementation((user) => Promise.resolve(user));
  handleSuccess = jest.fn();
  handleErrors = jest.fn();

  handleSubmit(handleSuccess, handleErrors); 

  expect(signupAPI).toHaveBeenCalled(); // test passes

  expect(handleSuccess).toHaveBeenCalled(); // test fails
});

When I run the test, it never moves to the 'then' part after the promise. How do I test that the function inside the then part is actually called?

How can testing a ASP.NET using Integrated Windows Authentication web app with LOCUST or GATLİNG

İ want to write load testing asp.net web app using gatling or locus but this app use windows authentication..

How can ı do that .. Thank you.

java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance

im stuck with following error. does someone know how to resolve this error?

18:36:30,635 ERROR [org.jboss.as.ejb3.invocation] (default task-1) WFLYEJB0034: EJB Invocation failed on component BootstrapTestService for method public abstract void *******.***.**.*******.service.provision.test.***********.provisionDB(boolean) throws java.lang.Exception: javax.ejb.EJBException: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance

mardi 26 février 2019

Element not found: Trying to verify a disabled button

Trying to verify this button if it is disable on the page :

<div class="btn-group pull-right" xpath="1"><div class="pull-right" style=""><input type="submit" ng-disabled="registrationForm.$invalid|| vm.payload.ConfirmPassword!=  vm.payload.Password|| vm.payload.ConfirmEmail!= vm.payload.Email|| vm.isAgreed== false|| vm.payload.GRecaptchaResponse== ''" class="btn btn-success btn-flat" value="Register and Continue" disabled="disabled" style=""></div></div>

But every time I run it, it says Element not found:(using katalon) Tried adding delay()/ waitForElement but got the same error.

This is the xpath I am using : //div[@class='btn-group pull-right']


WebUI.delay(10)

WebUI.verifyElementNotClickable(findTestObject('H3. Sign Up/H3.5 Providing correct details (Profile and Contact page) without checking Terms and Conditions and Captcha/Page_Demo Bookie (BETA)/Register And Continue Button'))


Can anyone help me or share any idea on how to fix this?

How to keep Unit tests and Integrations tests separate in pytest

According to Wikipedia and various articles it is best practice to divide tests into Unit tests (run first) and Integration tests (run second), where Unit tests are typically very fast and should be run with every build in a CI environment, however Integration tests take longer to run and should be more of a daily run.

Is there a way to divide these in pytest? Most projects don't seem to have multiple test folders, so is there a way to make sure I only run Unit, Integration or both according to the situtation (CI vs daily builds)? When calculating test coverage, I assume I will have to run both.

Am I going about this the right way in attempting to divide the tests into these categories? Is there a good example somewhere of a project that has done this?

question about commiting tests for react native on GIT

I have some tests that pass on my local machine. Now I want to "commit" the tests to GIT so I can have the CI/CD running the tests first.

My question is I cannot commit the test files to GIT.

There is nothing on

.gitignore

to ignore the tests...

Why are they not being committed to the repo?

modified:   src/Components/Checkbox/Text/__tests__/Text.js
modified:   src/Components/Checkbox/Text/__tests__/__snapshots__/Text.js.snap
modified:   src/Components/Checkbox/__tests__/CheckBox.js

I do

$git add .

$git commit -m "tests"

$git push

But the tests are not committed...

Testing datastructures with slices of complex types

I keep running into a problem where I have a complex data structure that has a slice of []Foo (where Foo is a complex struct) that can be accessed by a method Foos() []Foo, but then I want to consume this as a simpler interface (ex. []fmt.Stringer). However, even if foo implements fmt.Stringer, go can't use a []Foo as a []fmt.Stringer (even though it could use a Foo as a fmt.Stringer).

How can I write this in a testable way so I don't have to implement an entire mock Foo just to get fmt.Stringer functionality?

Simple example: `

type Foo struct {
    ...lots of fields...
}

... dozens of methods...

func (f Foo) String() string {
    return “this is foo”
}

type FooBox struct {
    ... lots of fields...
    foos []Foo
}

...dozens of methods...

func (fc FooBox) Foos() []Foo {
    return fc.foos
}

type fooBoxer interface {
    Foos() []fmt.Stringer
}

var _ fmt.Stringer = Foo{} // works
var _ fooBoxer = FooBox{} // does not compile, because the compiler can’t convert []Foo to []fmt.Stringer

`

SignalR Service mock implementation for Service/Integration testing

I want to be able to simulate SignalR Hub for services tests. The idea is to be able to create a test in the following way: Start a SignalR server (url, port and hub class should be configured at runtime) - the hub will be created in the test module for this purpose. So the first part - starting a runtime configurable SignalR server Is possible:

StartOptions so = new StartOptions("http://127.0.0.1:8080");
so.AppStartup = "SrServer.Startup1"; // set the startup class (will be defined in the test module)

The following is an example for Startup1:

class Startup1
{
    public void Configuration(IAppBuilder app)
    {

        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

The only issue I'm missing is being able to set the hub to be used from my test module - is this possible?

Dynamic placement test

I'd like to create a smart placement test where it decide the level of the next question based on the answer of the current question of it's correct or fault , but the point is there are questions that are important and questions that doesn't matter a lot . Any suggestions on how to start that ? or what to use to help me reach my goal .

thanks

What is the best practice to use sequential test-cases?

I know that, in test automation, we have to have avoid sequential test-cases.So, the order of running the test-cases are not important.

I believe in some cases the sequential test-cases is not avoidable:

Consider a scenario which a user needs to take some previous steps in order to complete a final goal. For example, a user needs to be logged in, so that he can purchase.

   Given User is logged in
   When  User adds an item into its basket
   And   User Complete his purchase
   Then  He receives an Email

So, in above scenario, each part (Given, When, And, and Then,) are seperate testcases. But still the order of testcase is crucial.

So, how do you write independent test-cases in end-2-end testing?

Testing in Scala (99 Scala problems)

I have just started a new job as an apprentice and have been tasked with learning scala. I have a very limited skillset in programming and the online material for learning scala as a beginner is limited. Could you guys walk me through the process of writing tests for the following problems as basically as you can as I learn well by example. Thanks in advance for your time and contributions :) ...

1) Find the last element of a list. Example: scala> last(List(1, 1, 2, 3, 5, 8)) res0: Int = 8

2) Find the last but one element of a list. Example: scala> penultimate(List(1, 1, 2, 3, 5, 8)) res0: Int = 5

3) Find the Kth element of a list. By convention, the first element in the list is element 0. Example:

scala> nth(2, List(1, 1, 2, 3, 5, 8)) res0: Int = 2

These are 3 of the "99 Scala Problems",hopefully this will help me complete the rest by myself.

Laravel 5.7 CSRF Middleware

According to Laravel 5.7 Docs

"The CSRF middleware is automatically disabled when running tests."

But I have the following Test

public function testUserLoginSuccesfully()
{
    $data = ['email' => 'test@user.com' , 'password' => bcrypt('test12345')];
    $csrf = csrf_token();

    $response = $this->withHeaders(['_token' => $csrf])
    ->post('/login',$data);

    $response->assertStatus(302)->assertRedirect('/home');

}

In order to work properly I have to disable csrf protection in the VerifyCsrfToken.php:

protected $except = [
    //
    '/login','/register'
];

If don't modify this property I'm getting a http 419 error. I don't know what I'm missing or how can I disable csrf only for testing.

Thanks in advance.

Enyme fails to find and simulate input change

Instead of changing the input enzyme inserts new variable into my TaskForm state with undifined key and the value that im trying to insert. My results looks like this

Expected value to equal: {"description": "new task description", "id": "", "title": "new task"} Received: {"description": "", "id": "", "title": "", "undefined": "new task"}

import React, { Component } from 'react';
const uuidv4 = require('uuid/v4')
//This is my component
class TaskForm extends Component {
  state = {
    title: '',
    description: '',
    id:''
  };
  onChange = e => this.setState({ [e.target.name]: e.target.value });
  resetForm = () => {
    this.setState({
      title:'',
      description:''
    })
  }
  onSubmit = e => {
      e.preventDefault()
      const task = this.state
      if(this.props.editTask){
        this.props.editTaskFunc(this.state)
      }else{
        this.setState(prevstate => ({
          id:uuidv4()
        }))
        this.props.addTask(this.state)
      }
      this.resetForm()
      this.props.closeToggle()
      
      
  }
  componentDidMount = () => {
    if(this.props.editTask){
      const {id,title,description} = this.props.editTask
      this.setState(
        prevState => ({
          id,
          title,
          description
        })
       
      );
    }
  }
  
  render() {
    const { title, description } = this.state;
    return (
      <form className="task-form" onSubmit={this.onSubmit}>
        <input name="title"  placeholder="Enter task title" type="text" value={title} onChange={this.onChange} required/>
        <input name="description" placeholder="Enter task description" type="text" value={description} onChange={this.onChange} required />
        <button>Submit</button>
        <button id="reset-btn" type="button" onClick={this.resetForm}>Reset</button>
      </form>
    );
  }
}

export default TaskForm;


//This is my test

import React from 'react';
import ReactDOM from 'react-dom';
import TaskForm from './TaskForm';
import { configure, shallow } from 'enzyme';

import Adapter from 'enzyme-adapter-react-16'
configure({adapter: new Adapter()});
const taskForm = shallow(<TaskForm/>)
describe('<TaskForm/>',() => {
  it('renders without crashing', () => {
    expect(taskForm).toMatchSnapshot()
  }); 
  it('renders  state inital empty array called tasks ', () => {
    expect(taskForm.state()).toEqual({
        title: '',
        description: '',
        id:''
    })
  });
   describe('entering input and reseting <TaskForm/> state',() => {

    beforeEach(() => {
        // taskForm.find("[name='title']").simulate('change',{target:{value:"new task"}})
        // taskForm.find("[name='description']").simulate('change',{target:{value:"new task description"}})
        taskForm.find("[name='title']").simulate('change',{target:{value:"new task"}})
    })
    afterEach(() => {
        taskForm.setState({
            title: '',
            description: '',
            id:''
          })
    })
       it('<TaskForm/> should have  changed state',() => {
        expect(taskForm.state()).toEqual({
            title: 'new task',
            description: 'new task description',
            id:''
        })
       })
    //    it('resets <TaskForm/> state on click',() => {
       
    //      taskForm.find('#reset-btn').simulate('click')
    //      expect(taskForm.state()).toEqual({
    //         title: '',
    //         description: '',
    //         id:''
    //     })
    //    })
   })
  
    
})

Protractor - How can i access an event data in Protractor

In my case I drag and drop a button, which fires an event. How can I fetch the event's data in protractor?

How to add a reference to a Form in NUnit unit testing, in C#?

I have a Form in C#, which has the following function:

    public bool SetAutomaticDownloadTimerEngine(int DownloadAtInterval)
    {
     //Do something here
    }

I want to test its behaviour using NUnit testing. For this, I had created a new project, added the reference and so on. In the NUnit test function, the code is this:

    [Test]
    public void SetTimesEngineTest()
    {
        //Arrange
        int flag = 1;
        bool Result = true;
        Form1 f = new Form1();

        //Act
        for (flag = -5; flag <= 10; flag++)
          Result = f.SetAutomaticDownloadTimerEngine(flag);

        //Assert
        if (flag == 1)
            Assert.AreEqual(Result, true);
        else
            Assert.AreEqual(Result, false);
        Assert.Pass();
    }

When I try to build this unit, I get the following error:

Error CS0012: The type 'Form' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

I tried adding System.Windows.Forms by using:

using System.Windows.Forms;

but I get the following error:

Error CS0234 The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

What am I missing here?

Way / Tool to test the web page that seems like web service endpoint

I am working on a project where the client provided the below URL as their endpoint and a sample payload, which I tried to run with SOAP UI and POST MAN without any luck.

My question is how can I test the webapp like this using the tools available in the market.

https://50.100.150.200:4444/TestService.aspx?MsgId=TestMessage&CompanyCode=250

<?xml version = '1.0' encoding = 'UTF-8'?>
<TestReq>
    <CompanyName>TestCompany</CompanyName>
    <CompanyAddress1>Street1</CompanyAddress1>
    <CompanyAddress2>Street2</CompanyAddress2>
    <CompanyCity>SampleCity</CompanyCity>
</TestReq>

Magento Functional Testing Framework

i am trying to install Magento Functional Testing Framework with the help of https://devdocs.magento.com/mftf/2.3/getting-started.html ,when i run vendor/bin/mftf build:project

i got this error

PHP Warning: require_once(/var/www/html/magento2): failed to open stream: No such file or directory in /var/www/html/magento2/vendor/bin/mftf on line 21 PHP Fatal error: require_once(): Failed opening required '' (include_path='.:/usr/share/php') in /var/www/html/magento2/vendor/bin/mftf on line 21

vendor/bin/mftf.php code

#!/usr/bin/env php


<?
 php 
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
if (PHP_SAPI !== 'cli') {
    echo 'bin/mftf must be run as a CLI application';
    exit(1);

}

$autoloadPath = realpath(__DIR__ . '/../../../autoload.php'); 
$testBootstrapPath = realpath(__DIR__ . '/../dev/tests/functional/standalone_bootstrap.php'); 

try {
    if (file_exists($autoloadPath)) {
        require_once $autoloadPath;
    } else {
        require_once $testBootstrapPath;
        //require_once ( 'db/config.php');
       // require_once __DIR__ . '/vendor/bin/mftf';

    }  
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}    


try {
    $application = new Symfony\Component\Console\Application();
    $application->setName('Magento Functional Testing Framework CLI');
    $application->setVersion('2.3.8');
    /** @var \Magento\FunctionalTestingFramework\Console\CommandListInterface $commandList */
    $commandList = new \Magento\FunctionalTestingFramework\Console\CommandList;
    foreach ($commandList->getCommands() as $command) {
        $application->add($command);
        }
        $application->run();
    } catch (\Exception $e) {
        while ($e) {      
            echo $e->getMessage();
            echo $e->getTraceAsString();
        echo "\n\n";
        $e = $e->getPrevious();
    }
    exit(1);
}

Converted XLS to testNG.XML file but when we execute xml from POM it will run old static testNG XML not dynamic generated XML

I have convert XLS data to XML and then try to run the runtime generated XML in framework.it will not pickup runtime generated XML and it will take old static XML and executed the code.Please help me to run the dynamic generated XML should run.

Botium Test Suddenly Stopped

I used Botium to test our chatbot. But in the middle of the process, the test suddenly stopped.

Not sure why "Stop called" even though my test haven't finished yet. This is what I got by running with --verbose.

2019-02-26T07:42:23.973Z botium-Convo Library Test wait for bot null
2019-02-26T07:42:24.202Z botium-connector-webdriverio Found new bot response element .vcw-message-container, id 0.9475738262354745-147
CHECKING ELEMENT 0.9475738262354745-147
2019-02-26T07:42:24.203Z botium-connector-webdriverio polling for bot output (.vcw-message-container)
FROM ME DECIDED 0.9475738262354745-147
no images: 0.9475738262354745-147
no audio: 0.9475738262354745-147
no video: 0.9475738262354745-147
    1) Library Test
2019-02-26T07:42:25.230Z botium-connector-webdriverio Stop called
2019-02-26T07:42:25.288Z botium-connector-webdriverio Clean called
2019-02-26T07:42:25.289Z botium-BaseContainer Cleanup rimrafing temp dir /var/lib/jenkins/workspace/botium-widget-prodtest/botiumwork/Production-Test-20190226-144119-7H0sV


  0 passing (1m)
  1 failing

lundi 25 février 2019

removing debugging symbols and debugging code from Android app (Ionic)?

Iam testing an ionic mobile app (Android version), and iam supposed to test : 1-The app catches and handles possible exceptions. 2-In unmanaged code, memory is allocated, freed and used securely. 3-Debugging code has been removed, and the app does not log verbose errors or debugging messages. 4-Debugging symbols have been removed from native binaries.

How could i do that ?

How to getting a log console all of test case when It has found error or warning message in Robot framework?

I had found an error and warning message in the console log and I would like to read some log error when It appears on Front-end.

How to not lose the purpose of a test case?

Looking into a code base over time, I started to worry that the test cases of it will become uninformative in the future. I foresee people in the future will ask: "What did they try to test here?"

A sample of confusing test case to me is:

public void convertAToB_unsupported() {
  String source = "src/test/data/12323.xml"
  checkNull(process(source));
}

That's it.

As for me, I usually do this way:

/**
 * Calling get into a non-empty list should give something. (TICKET-9812)
 */
public void shouldBeAbleToGetDataWhenNotEmpty() {
  // Given that the list is not empty
  List<Integer> list = new ArrayList<>();
  list.add(130);

  // When getting a data
  int first = list.get(0);

  // Then it should be possible
  assertThat(first, equalTo(130));
}

I don't know if this is sufficient or too much.

Could you share to me some best practices to ensure that the test remains informative in the future? Some links would be appreciated.

Mocked func returning promise with callFake doesn't enter then()

I have same method calls and am trying to write tests to mock MyService.getSoemthing in methodB(). However, it doesn't seem to work..

methodA(): any {
    methodB().then(() => {
        do something...
    })
}

methodB(): ng.IPromise<void> {
    return MyService.getSomething(a,b,c,d,e).then((result) => {
        ...does something with result...
        doesn't returning anything
    });
}

// With MyServiceMock injected
spyOn(MyServiceMock, 'getSomething').and.callFake(() => {
    return $q.resolve(result); // result is a variable that has already been init
});

or 

spyOn(MyServiceMock, 'getSomething').and.callFake((a,b,c,d,e) => {
    return $q.resolve(result); // result is a variable that has already been init
});

// then I call my methodA and ..
methodA();

It simply won't work.. I am able to debug until the resolution of the mock, it gets to resolve the promise but never ends up inside my ** ...does something with result... **

Any ideas?

Check if a view function was called

I'd like to test if my JS timer runs my timeout view:

    def testTimeLimit(self):
      self.client.get('/')
      response = self.client.get('/new',follow = True)
      sleep(2)
      #Assertion that checks if timeout view was called

How could I check what view functions were called in a session in chronological order? I know this test is easy to do in selenium but is it possible with a django.test.TestCase?

Jest test a component contains imported functions

I'm testing a component using Jest, here is the component I want to test:

<div className={'b-popover b-hover b-bottom'}>
    <div className={'b-content b-pull-left'}>
        <div className={'b-body bui-text-small'}>
            <FormattedMessage id={getStringByKey(GROUP_ASSIGNMENT_STRINGS, 'exceeding-fifty-groups-warning-tooltip-id')} defaultMessage={getStringByKey(GROUP_ASSIGNMENT_STRINGS, 'exceeding-fifty-groups-warning-tooltip')}/>
        </div>
    </div>
</div>

And here is my test code:

describe('When <GroupRow />', () => {

        it('it should structure the component correctly when input is disabled', () => {
            const props = {inputSectionType: ROW_INPUT_TYPE_DISABLED};
            const content = render(<GroupRow inputSectionType={props.inputSectionType}/>);
            expect(content).toMatchSnapshot();
        });
});

Inside FormattedMessage, here is a function getStringByKey(), and it is imported from ../../../constants. The functionality of getStringByKey() is not important at this time. But when I ran the test suite, I get the error :

TypeError: (0 , _constants.getStringByKey) is not a function

So how can I mock this function? Thanks.

Hard disk restore of a deleted btrfs partition

I have a situation where i ended up overwriting my main ssd of the workstation. Below is the chrnological order in which the system-partitions/ file-systems were created.

PROBLEM BACKGROUND/HISTORY

  1. GPT partition with 0%-33% , 33% to 66% and 66% to 100% partitions all btrfs type. some important data was stored in this partitions ( from here on refered to as the data
  2. I accidentally overwrote the whole disk with a new partion table and partitions , (2 to 3 times :( ) each partiton of 0 to 3% and 4% to 100% of GPT type and of FAT32 and ext4 file-systems respectively.

ISSUE:

With the above issue at hand i am trying to restore back to GPT - btrfs partitions mentioned in point "1" above

After initial research i am trying to use the testdisk software to restore back the deleted partions.

However upon selecting the particular partion to restore as listed below.

TestDisk 7.0, Data Recovery Utility, April 2015
Christophe GRENIER <grenier@cgsecurity.org>
http://www.cgsecurity.org

Disk /dev/xvdi - 240 GB / 223 GiB - CHS 29185 255 63
     Partition               Start        End    Size in sectors
 D MS Data                     2046  468860925  468858880
 D MS Data                     2048  468860927  468858880
 D MS Data                     2048  468860927  468858880 [NO NAME]
 D MS Data                     2054  468860933  468858880 [NO NAME]
 D MS Data                     4096     618495     614400
 D MS Data                     4102     618501     614400
>D MS Data                   618496     622591       4096 <==trying to restore this

If I press "P" at this point (as per the instructions on the test-disk website), i see the below screen. TestDisk 7.0, Data Recovery Utility, April 2015 Christophe GRENIER http://www.cgsecurity.org

     MS Data               618496     622591       4096



 Support for this filesystem hasn't been implemented.

Question:

How to restore data from deleted BTRFS file system partitions using testdisk or any other method.

Through put controller is not executing entire CSV file in jmeter

I have a test plan in which i am executing GET call on a server, i am reading data for GET calls from csv files.

My test plan is like enter image description here

I am dividing 100% among the five throughput controllers as

one -> 10
  one_one ->20
  one_two ->30
  one_three ->50
two ->20
  two_one ->40
  two_two ->60
three -> 45
  three_one ->20
  three_two ->30
  three_three ->20
  three_four ->30
four -> 10
  four_one ->100
five ->15
  five_one ->20
  five_two ->30
  five_three ->50

each of csv data set configure reads data from different files which contain variable number of lines (no. of lines is not same in all csv files), Now the PROBLEM is when any one of the csv file got completed then the test is getting stopped. I want to make the test run until all the csv files are completely read. CSV data set configuration is Recycle=false, stop at end of file=true, to make calls end when file reading is complete.

How to fix this problem

Change port for selenium tests

Im trying to set up selenium tests using zap, the webdriver should be firefox and the port 8080. But when it opens up the port is always a different number. This is the test below, I dont know how o open the browser under the port 8080 anfd firefox browser, the browser does actually open but nothing appears.

public class Sport {
WebDriver driver;
final static String BASE_URL = "https://web-test.com/";
final static String USERNAME = "test@hotmail.com";
final static String PASSWORD = "tables";

public Sport(WebDriver driver) {


    this.driver = driver;
    this.driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
    this.driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
}

public void login()throws Exception {
    driver.get(BASE_URL);
    Header header = new Header();
    header.guest_select_login();
    Pages.Login login = new Pages.Login();

    login.login_with_empty_fields();

    login.login_with_invalid_email();

    login.email_or_password_incorrect();


    login.login_open_and_close();
}

The Client zap api is working and starting it seems but the browser doesnt seem to open correctly to port 8080

public class ZapScanTest  {
static Logger log = Logger.getLogger(ZapScanTest.class.getName());
private final static String ZAP_PROXYHOST = "127.0.0.1";
private final static int ZAP_PROXYPORT = 8080;
private final static String ZAP_APIKEY = null;

// Change this to the appropriate driver for the OS, alternatives in the 
drivers directory
private final static String FIREFOX_DRIVER_PATH = "drivers/geckodriver.exe";
private final static String MEDIUM = "MEDIUM";
private final static String HIGH = "HIGH";
private ScanningProxy zapScanner;
private Spider zapSpider;
private WebDriver driver;
private Sportdec myApp;
private final static String[] policyNames = {"directory-browsing","cross- 
site-scripting","sql-injection","path-traversal","remote-file- 
inclusion","server-side-include",
"script-active-scan-rules","server-side-code-injection","external- 
redirect","crlf-injection"};
int currentScanID;


@Before
public void setup() {
    zapScanner = new ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
    zapScanner.clear(); //Start a new session
    zapSpider = (Spider)zapScanner;
    log.info("Created client to ZAP API");
    driver = DriverFactory.createProxyDriver ("firefox",createZapProxyConfigurationForWebDriver(), FIREFOX_DRIVER_PATH);

    myApp = new Sportdec(driver);
    //myApp.registerUser(); 
}

@After
public void after() {
    driver.quit();
}

@Test
public void testSecurityVulnerabilitiesBeforeLogin()throws Exception  {
    myApp.login();
    log.info("Spidering...");
    spiderWithZap();
    log.info("Spider done.");

    setAlertAndAttackStrength();
    zapScanner.setEnablePassiveScan(true);
    scanWithZap();

    List<Alert> alerts = filterAlerts(zapScanner.getAlerts());
    logAlerts(alerts);
    assertThat(alerts.size(), equalTo(0));
}

ReferenceError JWTAPIFunc is not defined

So I've been tasked with testing an express app that contains an AWS Lambda. I'm trying to test two methods in a file that look like this.

Validator.js

const Verifier = require('@companyName/api-jwt-validation');

JWTAPIFunc = function(callType){
  return function (req,res,next){
    .
    .
    .
    try {
    .
    .
    .
    } catch (authorizationError) {
        .
        .
        .
    }
  }
}

module.exports = {
      JWTAPIFunc:JWTAPIFunc
};

I want to test this JWTAPIFunc using jest so I have a test file that looks like this

Validator.test.js

const Verifier = require('@companyName/api-jwt-validation');
const Validator = require('../Validator')
jest.mock(Verifier);


test('Do something', ()=>{

});

When I run this empty test I get this error

● Test suite failed to run

ReferenceError: JWTAPIFunc is not defined

  1 | const Verifier = require('@companyName/api-jwt-validation');
  2 | 
> 3 |  JWTAPIFunc = function(callType){
    |                 ^
  4 |     return function (req,res,next){


  at Object.<anonymous> (src/Validator.js:3:17)
  at Object.<anonymous> (src/__tests__/Validator.test.js:3:1)

Why is it saying that this function is not defined? Sorry again if this is a stupid question.

How to mock a Sails.js / Waterline Model during testing

I am trying to mock a Sails Model using sinon.js. I have a problem when I am testing the part where I'm using .fetch() alongside Model.create() to retrieve the newly created row.

Here is my code I want to mock:

...
let newObject = await Object.create(newObjectData).fetch();
...

Here is my test code

const sinon = require('sinon');
const supertest = require('supertest');

describe('Object create action', function() {
  let sandbox;
  beforeEach(function() {
    sandbox = sinon.createSandbox();
  });
  afterEach(function() {
    sandbox.restore();
  });

  it('should create Object', function(done) {

    const objectCreateStub = sandbox.stub(Object, 'create').callsFake(async function(data) {
      console.log(data);
      return {
        key: 'value'
      };
    });
    supertest(sails.hooks.http.app)
      .post(`/objects`)
      .send({
        key: 'value'
      })
      .expect(200)
      .end(done);
  });
});

I have no idea what the Object.create faked function should return in order to .fetch to not throw an error. So, as expected I get this error:

TypeError: Object.create(...).fetch is not a function

What kind of object does Model.create() returns so I could mock it too? Is there a best practice somewhere for testing with Sails and Waterline?

Thanks!

Postman Tests - Conditioning with http status

I want to check if an answer is ok. It is either correct when the response code is 200 or 500. Latter needs to differentiate between a String in the response body to be correct or incorrect. It should be in a single test.

I already tried simple if-clauses, but they do not work.

pm.test("response is ok", function(){
    if(pm.response.to.have.status(200)){
        //do things
    }     
});

Access JSON serializer configured in ASP.NET Core

I have an API controller that returns instance of a class ExampleDataType. The default behavior is that the object is serialized to JSON and that's fine.

API controller snippet:

[Route("api/[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
    [HttpGet]
    public ExampleDataType Get()
    {
        return new ExampleDataType();
    }
}

I would like to slightly change the way of object serialization (property casing). I configured JSON serializer built in ASP.NET Core application in following way:

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                options.UseMemberCasing();
            });
    }

So far so good. Now, I would like to create a (unit?) test that would document intended behavior. My idea for such test is:

  1. Access the JSON serializer with applied customizations in Server.
  2. Use the serializer on a test class instance.
  3. Assert the results.

I already know how to spawn a test, in-memory server instance with WebApplicationFactory. Alas, I don't know how to access the serializer configured in server.

Any ideas?