lundi 29 juin 2015

Node.js - Unit Testing Middleware

I have an api with a middleware function which I use to filter incoming requests. The functions checks the present of a token in the header, then makes two calls to the database, one to check the token and one to get some information and pass it on to the request object, if the 1st call was successful.

I am struggling to understand how to unit test this functions, by mocking up the request object and also the database calls.

middleware.js

exports.checkToken = function (req, res, next) {
  if (!req.get('token')) {
      return res.status(400).json('Bad request');
  }

  var token = req.get('token'); //get token from the header 

  User.findOne({'token': token}, function(err, user) {
      // skipped error checking or no user found
      Account.findOne({'_id': user.account}, function(err, account) {
          // skipped error checking or no account found
          req.somevalue = account;
          return next();
      });
  });
};

Currently I am using mocha, chai and sinon and was thinking of the following:

  • mock User.findOne and Account.findOne using sinon.stub()

  • not really sure what to do about the req, res and next objects. How to emulate these?

WebApi Unit Test HttpContextHelper with Mock

I have a method I'm trying to mock for unit testing but I'm having difficulty as all the props are read only and mocking fails as it is a sealed class. This method is hung off a controller and I have all that infrastructure in place.

First here is the method I'm trying to test.

public CarResponse(Common.Models.Car car)
{
    string currentAcceptType = HttpContextHelper.Current.Request.Headers["Accept"];

    ....removed for brevity.....

}

I have tried to inject an instantiated object and that would work but my Headers are read only so I can't see how to set the headers to what I want??

HttpRequest cv = new HttpRequest(null, "http://localhost:24244", "/cars/_services/addNewPickup");
//so far so good but then when I want to add my headers every property is read only.
cv.Headers.Add("qewr", "adsf"); //This fails.

MSDN

Ultimately I would be using it as part of the larger fake "session" for testing.

HttpContext.Current = new HttpContext(cv, new HttpResponse(null));

Mocking of HttpRequest fails as it is a sealed class.

So I'm kinda stumped on how to test this unit of code.

How to create CSRF token for Cakephp 3 PHPunit testing?

I am trying to get my unit tests working again after enabling CSRF tokens and SSL in my CakePHP 3 app.

How do I create or generate a token for a test like the following? Or do I just disable it for testing purposes?

public function testLogin() {
    $this->get('/login');
    $this->assertResponseOk();

    $data = [
        'email' => 'info@example.com',
        'password' => 'secret'
    ];
    $this->post('/login', $data);

    $this->assertResponseSuccess();
    $this->assertRedirect(['controller' => 'Users', 'action' => 'dashboard']);
}

Keep Mocha tests alongside to source files

I currently have my NodeJS source files in src and test suites in test, e.g.:

/src/bar/baz/foo.js
/test/bar/baz/foo.spec.js

This leads to awkward require statements like var foo = require('../../../src/bar/baz/foo'). And it's hard to see at a glance which source files are missing tests. I would like to instead keep my test suites in the same directory as the relevant source files:

/src/bar/baz/foo.js
/src/bar/baz/foo.spec.js

But now running mocha --recursive src causes errors as Mocha tries to run my source files as tests.

I've seen suggestions of using find or gulp to filter the file list but I find it surprising that this can't be done with plain Mocha. What's the recommended way of organising files this way?

no "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, " even that cucumber test was executed using "mvn test" command

Hi
Could someone suggest me a solution why when I run the test using command "mvn test" to run the cucumber runner class "ExampleRunnerTest" located in \src\test\java it runs but the maven build doesn't recognize it. Like I said the test runs does what it should do but the build still fails

1 Scenarios (←[32m1 passed←[0m)
6 Steps (←[32m6 passed←[0m)
1m36.764s
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 98.777 sec - in BasicTest
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/java/cucumber/feature/Basic.feature", glue = "cucumber/stepDefinition",
    format = {"pretty", "html:target/cucumber", "json:target/cucumber-report.json"})

public class BasicTest {
}

Configure test folder for unit testing in Android studio

I have added a folder for unit testing in my android studio project. The default folder is andoidTest but I have added a new folder and name in test instead. (like robolectric sample tests)

When I add test Dependency in my build.gradle under module such as

testCompile("junit:junit:${junitVersion}")
testCompile ("org.robolectric:robolectric:${robolectricVersion}")

They do not get added to external libraries under project, but when I use the default configuration and use androidTestCompile, it can added external libraries.

Then I thought that maybe I should setRoot for tests in gradle, so I used following in android tag in build.gradle:

sourceSets {
        androidTest.setRoot('src/test')
}

But still problem remained. I can run tests using gradlew, but imports in classes in test folder do not apply as well as no external library for test purpose is visible.

Anyone have any solution for this issue?

Unit testing (non-Qt) C++ code in Qt Creator?

I have a C++ project that doesn't use Qt. I am using Qt Creator as my IDE because it is very convenient. I was reading about unit testing in Qt Creator here, and I think that Qt Test seems quite good. Is there a way to use Qt Test with my non-Qt C++ project?

Also, a feature that I liked when I was using Visual Studio is that the tests are run automatically everytime I build my project. Can I do the same with Qt Creator?