EzDevInfo.com

vows

Asynchronous BDD & continuous testing for node.js Vows « Asynchronous BDD for Node

How do you mock MySQL (without an ORM) in Node.js?

I'm using Node.js with felixge's node-mysql client. I am not using an ORM.

I'm testing with Vows and want to be able to mock my database, possibly using Sinon. Since I don't really have a DAL per se (aside from node-mysql), I'm not really sure how to go about this. My models are mostly simple CRUD with a lot of getters.

Any ideas on how to accomplish this?


Source: (StackOverflow)

Using Vows to test Mongoose models

Fairly new to the whole node.js community, and I'm having trouble with my unit tests on my first app. The problem is they pass, but they never actually run the assertions in the callbacks. As I understand it, mongoose (the library I'm using to talk to MongoDB) uses callbacks for working with it's API. In my vows tests, these callbacks don't seem to get fired. An example:

vows = require 'vows'
assert = require 'assert'
mongoose = require 'mongoose'

ProjectSchema = new Schema
  name: String    
Project = mongoose.model 'Project', ProjectSchema

mongoose.connect('mongodb://localhost/testdb');


projectBatch = vows.describe('Project').addBatch 
  'model attributes':
    topic: ()->
      new Project()
  'should have a name field': (topic)->
    topic.name = "some name"
    topic.save
    console.log "this gets executed just fine"
    Project.findById topic.id, (error, project)->
      console.log "THIS LINE NEVER RUNS!"
      assert.equal "some name", project.name

projectBatch.export module

Any ideas on what I'm doing wrong here?


Source: (StackOverflow)

Advertisements

How to solve "callback not fired" with Vows and Node.js

I'm trying to get started with Vows and Vows-BDD. Unfortunately, the callbacks are tripping me up.

In the very simple example below, how does one fix this error?

** Inside the first context
** Creating Person with name Nick

✗ Errored » callback not fired
      in Create a Person via JavaScript: When a person has a name,
      in Creating a Person
      in undefined✗ Errored » 1 errored  1 dropped
vows_bdd  = require "vows-bdd"
assert    = require "assert"


class Person
  constructor: (@name) ->
    console.log "** Creating Person with name #{@name}"

  greeting: ->
    "Hello, #{@name}"


vows_bdd
  .Feature("Creating a Person")
    .scenario("Create a Person via JavaScript")

    .when "a person has a name", ->
      console.log "** Inside the first context"
      new Person "Nick"

    .then "the person can be greeted", (person) ->
      console.log "person is a #{typeof person} = [#{person}]"
      assert.equal person.greeting(), "Hello, Nick"

    .complete()
    .finish(module)

Source: (StackOverflow)

Error in writing asynchronous Vows.js Tests

I have been working with node and using vows to write tests.

var vows = require('vows');
var assert = require('assert');

var boardData = require('../lib/data/BoardData.js');

vows.describe('Loading provinces and Boundries for').addBatch({
  'version': {
    '2008E5-1':{
      topic: function () { boardData.createBoard("2008E5",this.callback); },
      'exists': function (err,provs,bounds) { assert.ok(true); }
    }/*,
    '2008E5-2': {
      topic: function () { boardData.createBoard("2008E5",this.callback); },
      'exists': function (err,provs,bounds) { assert.ok(true); }
    }*/
  }
}).export(module);

When I Run this code I get the expected results. When I uncomment the commented section notice that two completed successfully but one can discover that is the second one twice by placing a console.log("foo"); in the proper location.

·· ✓ OK » 2 honored (0.067s)
·
✗ Errored » callback not fired
  in version 2008E5-1
  in Loading provinces and Boundries for
  in undefined

This must be that I am missing something or lack the understanding of something, but I cannot figure it out. Can anyone help me? Thanks in advance!


Source: (StackOverflow)

Command not found after npm install in zsh

I'm having some problems installing vows via npm in zsh. Here's what I get. I tried installing it with and without the -g option. Do you have any idea what's wrong here?

[❤  ~/Desktop/sauce-node-demo:master] npm install -g vows
npm http GET https://registry.npmjs.org/vows
npm http 304 https://registry.npmjs.org/vows
npm http GET https://registry.npmjs.org/eyes
npm http GET https://registry.npmjs.org/diff
npm http 304 https://registry.npmjs.org/eyes
npm http 304 https://registry.npmjs.org/diff
/usr/local/share/npm/bin/vows -> /usr/local/share/npm/lib/node_modules/vows/bin/vows
vows@0.6.4 /usr/local/share/npm/lib/node_modules/vows
├── eyes@0.1.8
└── diff@1.0.3
[❤  ~/Desktop/sauce-node-demo:master] vows
zsh: command not found: vows

Thanks


Source: (StackOverflow)

Async testing with vows using the http.get library in Node.js

I'm having a doozie of a time trying to get a basic http test to work with vows.

I think I've followed the async example from vows http://vowsjs.org/#-writing-asynchronous-tests and substitued the appropriate calls, but I must be missing something.

The test code looks like this:

var http = require('http'),
    vows = require('vows'),
    assert = require('assert');

vows.describe("homepage").addBatch({
  "Get the home page": {
    topic: function() {
      http.get({'host': "127.0.0.1", 'port': 5000, 'path': '/'}, this.callback);
    },
    'should respond with 200 OK': function(res) {
      assert.equal(res.statusCode, 200);
    }
  }
}).export(module);

I get the following error when I try to run the test for this:

/Users/<home_folder>/node_modules/vows/lib/vows.js:80
rrored', { type: 'promise', error: err.stack || err.message || JSON.stringify(
                                                                    ^
TypeError: Converting circular structure to JSON
    at Object.stringify (native)
    at EventEmitter.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows.js:80:90)
    at EventEmitter.emit (events.js:64:17)
    at /Users/<home_folder>/node_modules/vows/lib/vows/context.js:31:52
    at ClientRequest.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows/context.js:46:29)
    at ClientRequest.g (events.js:143:14)
    at ClientRequest.emit (events.js:64:17)
    at HTTPParser.onIncoming (http.js:1349:9)
    at HTTPParser.onHeadersComplete (http.js:108:31)
    at Socket.ondata (http.js:1226:22)

I can get a simple http example to work on it's own. I can get the vows example to work on it's own but I can't combine them for whatever reason. I'd really appreciate some help here. I've been trying to get this to work for a while now (including much googling).

UPDATE:

Apparently adding an error argument to the call back solves this problem, thanks to help from Alexis Sellier (creator of vows).

But I have no idea why. When writing out the http lib example on it's own no error argument is required. I can't find any documentation in vows to indicate why it's needed so I'm at a bit of a loss.

My new question is why is the error argument required when using the http lib in vows?


Source: (StackOverflow)

Vows with Async nested topics - scope problem

I want my vow to have access to outerDocs and innerDocs from my topics but it doesn't.

'ASYNC TOPIC': {
  topic: function() {
    aModel.find({}, this.callback);
  },
  'NESTED ASYNC TOPIC': {
    topic: function(outerDocs) {
      anotherModel.find({}, this.callback(null, innerDocs, outerDocs));
    },
    'SHOULD HAVE ACCESS TO BOTH SETS OF DOCS': function(err, innerDocs, outerDocs) {
      console.log(err, innerDocs, outerDocs);
      return assert.equal(1, 1);
    }
  }

What am I doing wrong?


Source: (StackOverflow)

In vows, is there a `beforeEach` / `setup` feature?

Vows has an undocumented teardown feature, but I cannot see any way to setup stuff before each test (a.k.a. beforeEach).

One would think it would be possible to cheat and use the topic, but a topic is only run once (like teardown), whereas I would like this to be run before each test. Can this not be done in vows?


Source: (StackOverflow)

I can't run test with "vows test/*" command on windows. How to use it? node.js

I've installed vows as module of my project and I've added the path "node_modules\vows\bin" to my environment path variable of windows vista.

note: I've also renamed "node_modules\vows\bin\vows" to vows.exe, because without the extension I get this error: 'vows' is not recognized as an internal or external command, operable program or batch file.

Now wherever I put "vows" in my cmd in windows nothing happens, I cd into my test folder and I run "vows myFirstTest.js" and nothing happens. (when I say nothing happens my cursor in cmd is going to the top and then return to it's original position and it's doing this forever, therefore each time I try a vows command in cmd I have to close the cmd to run another command).

What I'm doing bad?

thanks


Source: (StackOverflow)

Testing MongooseJs Validations

Does anyone know how to test Mongoose Validations?

Example, I have the following Schema (as an example):

var UserAccount = new Schema({
    user_name       : { type: String, required: true, lowercase: true, trim: true, index: { unique: true }, validate: [ validateEmail, "Email is not a valid email."]  }, 
    password        : { type: String, required: true },
    date_created    : { type: Date, required: true, default: Date.now }
}); 

The validateEmail method is defined as such:

// Email Validator
function validateEmail (val) {
    return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(val);
}

I want to test the validations. The end result is that I want to be able to test the validations and depending on those things happening I can then write other tests which test the interactions between those pieces of code. Example: User attempts to sign up with the same username as one that is taken (email already in use). I need a test that I can actually intercept or see that the validation is working WITHOUT hitting the DB. I do NOT want to hit Mongo during these tests. These should be UNIT tests NOT integration tests. :)

Thanks!


Source: (StackOverflow)

How to use a diferent reporter with Vows' run() method?

Vows has a run() method that runs the test under node, without using the vows command.

At https://github.com/cloudhead/vows/blob/master/lib/vows/suite.js we can see that this method takes an option parameter which allows to specify a reporter other than the default:

this.run = function (options, callback) {
    var that = this, start;

    options = options || {};

    for (var k in options) { this.options[k] = options[k] }

    this.matcher  = this.options.matcher  || this.matcher;
    this.reporter = this.options.reporter || this.reporter;

What value is supposed to be passed in the options object to select a diferent reporter, for instance the spec reporter?


Source: (StackOverflow)

Is this the correct way to do Dependency Injection in Node?

I recently started a node project and as a Test-Driven Developer, I quickly ran into a dependency injection problem with my brand new module. Here's how I figured out I should do dependency injection. It's important to note I'm using vows as BDD framework and extend it with Sinon.

My module:

exports.myMethod = function () {
  var crypto = exports.cryptoLib || require('ezcrypto').Crypto;
  crypto.HMAC(
    crypto.SHA256,
    'I want to encrypt this',
    'with this very tasty salt'
  );
};

My test:

var vows = require('vows'),
  sinon = require('sinon');

vows.describe('myObject').addBatch({
  'myMethod':{
    'topic':true,
    'calls ezcrypto.HMAC':function () {
      var myObject = require('../playground.js');
      var mock = sinon.mock(require('ezcrypto').Crypto);

      myObject.cryptoLib = mock;
      myObject.cryptoLib.HMAC = mock.expects("HMAC").once().withExactArgs(
        require('ezcrypto').Crypto.SHA256,
        'I want to encrypt this',
        'with this very tasty salt'
      );
      myObject.cryptoLib.SHA256 = require('ezcrypto').Crypto.SHA256;
      myObject.cryptoLib = mock;
      myObject.myMethod();
      mock.verify();
    }
  }
}).export(module);

Do you think this the correct way to go? I like this solution because it doesn't require more when you use the module (like adding "()" after the require statement).


Source: (StackOverflow)

Should I switch from Vows to Mocha?

I'm trying to decide whether to switch from Vows to Mocha for a large Node app.

I've enjoyed almost all of the Vows experience - but there is just something strange about the argument passing. I always have to scratch my head to remember how topics work, and that interferes with the basics of getting the tests written. It is particularly problematic on deeply nested asynchronous tests. Though I find that combining Vows with async.js can help a little.

So Mocha seems more flexible in its reporting. I like the freedom to choose the testing style & importantly it runs in the browser too, which will be very useful. But I'm worried that it still doesn't solve the readability problem for deeply nested asynchronous tests.

Does anyone have any practical advice - can Mocha make deeply nested tests readable? Am I missing something?


Source: (StackOverflow)

Namespaces in node.js with require

I am playing around and learning about vows with a personal project. This is a small client side library, with testing done in vows. Therefore, I must build and test a file that is written like this:

(function(exports) { 
    var module = export.module = { "version":"0.0.1" }; 
    //more stuff
})(this);

In my testing (based off of science.js, d3, etc.) requires that module like so:

require("../module");

I continued to get a "module not defined error" when trying to run the tests, so I went to a repl and ran:

require("../module")

and it returned:

{ module: { version: "0.0.1" } }

I realize I could do something like:

var module = require("../module").module;

but feel like I am creating a problem by doing it that way, especially since the libraries that I based this project on are doing it in the format I described.

I would like for my project to behave similar to those which I based it off of, where:

require("../module");

creates a variable in this namespace:

module.version; //is valid.

I have seen this in a variety of libraries, and I am following the format and thought process to the T but believe I might be missing something about require behavior I don't know about.


Source: (StackOverflow)

Jasmine, Mocha, and Vows feature comparison [closed]

Would anyone be willing to give a listing of the differences between these three Javascript testing frameworks?


Source: (StackOverflow)