EzDevInfo.com

teaspoon

Teaspoon: Javascript test runner for Rails. Run tests in the browser or headless with PhantomJS, Selenium WebDriver or Capybara Webkit.

Stubbing $.get function using teaspoon

I have a javascript function like the one below

function_name: function(){
    var self = this;
    $.get('something',{
        target : 'something',
        param1 : 'somevalue',
    })
}

I need to stub $.get function using teaspoon. could I get any snippet to solve using teaspoon or sinon stub

Updated

I was able to solve this issue using the following code

var ajax_get_stub = sinon.stub($, 'get').returns($.Deferred().resolve({}).promise());

expect(ajax_get_stub.withArgs('resource', { param1: 'value' }).calledOnce).to.be(true);

$.get.restore();

Source: (StackOverflow)

Jenkins not running istanbul JS code coverage tool

I am using Teaspoon + Istanbul JS code coverage tool for Ruby project,which has more JS code in it.

I have installed istanbul using $ npm install -g istanbul commend on the jenkins box.

If the run bundle exec teaspoon, it works fine on local and producing JS codo coverage report nicely.

But when i run the same command thru jenkins shell, its not produce any report.

$istanbul help throw command not found on the jenkins


Source: (StackOverflow)

Advertisements

Invalidating an Ember Simple Auth session while testing

Typically, when you invalidate an Ember Simple Auth session, it'll reload the application. This is great for security in production, but while testing, it can be a headache. I'm running my tests using Teaspoon, and any time I logout a test user, Ember Simple Auth reloads the app--essentially terminating the test suite.

Has anyone found a workaround for this?


Source: (StackOverflow)

Which gem should be used for testing javascript with rails jasminerice or jasmine-rails or teaspoon?

I'm getting in to testing javascript in rails 4, but it seems there are two options. The jasminerice gem, which looks like it's been round for a while but maybe not so up to date and the jasmine-rails gem which looks like it's being released more often. Should I use jasminerice or jasmine-rails?

Update From my searching round, it looks like teaspoon is the new popular kid on the block: https://github.com/modeset/teaspoon


Source: (StackOverflow)

angular mock `module` resulting in '[Object object] is not a function'

I'm trying to create some unit tests in Angular using Jasmine being run through Teaspoon. The tests are running, however I have a simple test just to test the existence of a controller that is failing. I have the following test setup.

//= require spec_helper

require("angular");
require("angular-mocks");
var app = require("./app");


describe("My App", function() {

  describe("App Controllers", function() {

    beforeEach(module("app"))

    it("Should have created an application controller", inject(function($rootScope, $controller){
      var scope = $rootScope.$new();
      ctrl = $controller("ApplicationCtrl", { $scope: scope });
    }));

  })

})

The require statements are processed by Browserify which is handling my dependencies, but I can also hook into sprockets which I'm using for the spec helper.

Inside the app that is being required, I have

require("angular");
var controllers = require("./controllers");

var app = angular.module("app", [
  "app.controllers"
]);

exports.app = app;

When I run this test, I get the following error produced

Failure/Error: TypeError: '[object Object]' is not a function (evaluating 'module("aialerts")')

I've spent quite a while trying to figure this out but I have no idea what's going on. Any help appreciated.


Source: (StackOverflow)

VCR-like (cache and replay external requests) tool for testing browser javascript

There is a beautiful tool for recording test suite's backend HTTP interactions and replay them during future test runs. It is VCR. Its analogs are implemented in many different language including Javascript (nodejs based apps).

There is also similar solution for integration (capybara-based) tests for Ruby app, puffing-billy. It is rewriting web proxy for testing interactions between browser and external sites, behave like VCR.

But I'm interesting in VCR-like behavior for frontend tests. I'm talking about JavaScript tests, for example Jasmine specs.

My JS code heavily use external JS libraries that creates AJAX requests to external web-services. I want't to cache and replay external cites responses in my tests.

Now I'm using headless spec runner based on PhantomJS (teaspoon). And if I try to use some JavaScript VCR implementation (vsr.js, for example) I always catch an error when implementation is trying to interact with filesystem (var fs = require('fs');)

ReferenceError: Can't find variable: require

I see several solutions:

  1. Extract proxy from puffing-billy, configure phantomjs to use that proxy, and then run that proxy before running test suite.
  2. Migrate to some NodeJS-based javascript tests runner for Rails applications (if any) and use some VCR-like solution for NodeJS.

But none if it is good enough, because I don't know any NodeJS-based javascript test runner for Rails and I want to avoid extracting proxy from any library.

So question is: are the some VCR-like solutions for testing browser javascript (ideally prepared for Rails)? And what is the best option for such task?


Source: (StackOverflow)

Qunit testing an Ember.js app with ember-simple-auth authentication?

So, Am writing a Qunit test (with teaspoon as the test runner), for an Ember application that uses ember-simple-auth gem for login authintication, My test is as follows (coffee script) :

#=  require qunit_spec_helper

test "Employee signs in", ->
  expect(1)
  visit("/login").then(->
    fillIn "input.email", "employee1@example.com"
  ).then(->
    fillIn "input.user_password", "password1"
  ).then(->
    click "button.btn-primary"
  ).andThen ->
   equal(find('h2').length,1, "Welcome to the App")

And here is the Test helper:

QUnit.testStart ->

  Ember.run ->
    App.reset()

  Ember.testing = true
    App.setupForTesting()
    App.injectTestHelpers()

QUnit.testDone ->
  Ember.testing = false

QUnit.done ->
  Ember.run ->
    App.reset()

When I run the test (keeping any eye on the console), I get the following error:

POST http://localhost:3000/teaspoon/qunit/oauth/token 404 (Not Found)

I can't seem to be able to login, No matter what .. I ran out of ideas, Any help/Advice is highly Appreciated :)


Source: (StackOverflow)

Using Syn library to simulate drag and drop on Qunit/PhantomJS

I keep getting this same error -> Argument 1 of Document.elementFromPoint is not a finite floating-point value.

I am trying to drag the 'group' element to the addGroupBtn. However I can't seem to get any simulation to work, I even ran in teaspoon browser and still obtain the same error. I tested in console but couldn't achieve the results. Maybe its just a syntax error or misunderstanding of documents on my part. Also the framework is ruby on rails using ember.js

Here is the documentation to this library: http://v3.javascriptmvc.com/docs.html#&who=Syn.drag

group = $("#group-0-header").children("i")
addGroupBtn = $("#add-group")
Syn.click({}, group).drag(group, addGroupBtn, {})

Source: (StackOverflow)

Teaspoon showing some weird error on CircleCI

I am using teaspoon for some javascript testing (written in CoffeeScript) on my development machine everything works great:

→ bundle exec rake teaspoon
Starting the Teaspoon server...
Teaspoon running default suite at http://127.0.0.1:58786/teaspoon/default
................

Finished in 0.02500 seconds
16 examples, 0 failures

But on the CircleCI it ends with following error.

$ bundle exec rake teaspoon --trace
** Invoke teaspoon (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute teaspoon
Starting the Teaspoon server...
Teaspoon running default suite at http://127.0.0.1:60894/teaspoon/default
Failed to load: http://127.0.0.1:60894/teaspoon/default?reporter=Console bundle exec rake teaspoon --trace returned exit code 1

Can anyone help me with this error? Thanks


Source: (StackOverflow)

Emberjs tests hang when running through CLI

My Ember test suite is timing out when I run it through the command line. I've tracked this down and it's due to ajaxComplete not firing for an AJAX request that is kicked off through a call to visit, but this same request fires the complete event fine when running through the browser.

The ajaxComplete event triggers a call to Ember's decrementAjaxPendingRequests and when that's not called it will continually spin during the wait method as Test.pendingAjaxRequests requests is not 0. You can see that here:

    function wait(app, value) {
      return Test.promise(function(resolve) {
        // If this is the first async promise, kick off the async test
        if (++countAsync === 1) {
          Test.adapter.asyncStart();
        }

        // Every 10ms, poll for the async thing to have finished
        var watcher = setInterval(function() {
          console.log("watcher tick");
          // 1. If the router is loading, keep polling
          var routerIsLoading = !!app.__container__.lookup('router:main').router.activeTransition;
          if (routerIsLoading) { 
            return; 
          }

          // 2. If there are pending Ajax requests, keep polling
          if (Test.pendingAjaxRequests) { 
            console.log("PENDING AJAX REQUESTS: ", Test.pendingAjaxRequests, " - RETURNING");
            return;
          }

          // 3. If there are scheduled timers or we are inside of a run loop, keep polling
          if (run.hasScheduledTimers() || run.currentRunLoop) {
            return;
         }

          if (Test.waiters && Test.waiters.any(function(waiter) {
            var context = waiter[0];
            var callback = waiter[1];
            return !callback.call(context);
          })) { 
            return;
          }
          // Stop polling
          clearInterval(watcher);


          // If this is the last async promise, end the async test
          if (--countAsync === 0) {
            Test.adapter.asyncEnd();
          }

          // Synchronously resolve the promise
          run(null, resolve, value);
        }, 10);
      });

    }

The AJAX request in question is from a model hook in one of my routes and it's a simple return this.store.find('model_name'). I'm using sinon.js to fake this request out and I'm seeing it return correctly if I put a then clause on that find call, but it still is not firing it's ajaxComplete event.

Here is my stack:

  • Ember: 1.7.1
  • Ember-Data: 1.0.0-beta.8.2a68c63a
  • Teaspoon (My test runner): 0.8.0
  • jQuery: 1.10.2
  • PhantomJS (CLI Test Runner): 1.9.7 && 1.8.2

Does anybody know if there is any open issue for this or what specific part of the stack could be causing it? I'm at a loss for where to go from here.


Source: (StackOverflow)

Guard spec/javascripts tests only run tests the first time

I am trying to get guard to work with Jasmine tests. I have tried guard-jasmine with jasminerice, guard-jasmine with jasmine-rails, and teaspoon. I end up getting the same error - the tests work the first time I set up guard, but every time I save a spec file or a javascript file the tests do not update. This is true when I run the tests in guard, or if I run it in a browser (i.e. /jasmine for jasmine-rails or /teaspoon for teaspoon), the tests work when I run rails s, but do not update the tests when I save them and refresh the page.

I only see this behavior in my spec/javascripts directory, when I run a test in like spec/controllers, guard works as expected.

Any suggestions on what might be the problem?

Here is my Guardfile:

# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard 'livereload' do
  watch(%r{app/views/.+\.(erb|haml|slim)$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{config/locales/.+\.yml})
  # Rails Assets Pipeline
  watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html|sass))).*}) { |m| "/assets/#{m[3]}" }
end

guard :teaspoon do
  # Implementation files
  watch(%r{app/assets/javascripts/(.+).js}) { |m| "#{m[1]}_spec" }

  # Specs / Helpers
  watch(%r{spec/javascripts/(.*)})
end

guard 'rspec', all_after_pass: false, all_on_start: false, bundler: true, cli: "--color --format=doc" do
  watch(%r{^spec/.+_spec\.rb$})
  watch(%r{^lib/(.+)\.rb$})     { |m| "spec/lib/#{m[1]}_spec.rb" }
  watch('spec/spec_helper.rb')  { "spec" }

  # Rails example
  watch(%r{^app/(.+)\.rb$})                           { |m| "spec/#{m[1]}_spec.rb" }
  watch(%r{^app/(.*)(\.erb|\.haml)$})                 { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
  watch(%r{^app/controllers/(.+)_(controller)\.rb$})  { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
  watch('config/routes.rb')                           { "spec/routing" }
  watch('app/controllers/application_controller.rb')  { "spec/controllers" }
  watch(%r{^app/views/(.+)/}) { |m| "spec/requests/#{m[1]}_spec.rb" }

  # Capybara request specs
  #watch(%r{^app/views/(.+)/.*\.(erb|haml)$})          { |m| "spec/requests/#{m[1]}_spec.rb" }

  # Turnip features and steps
  #watch(%r{^spec/acceptance/(.+)\.feature$})
  #watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$})   { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end

Thank you,


Source: (StackOverflow)

Visit pages using PhantomJS directly when writing specs with TeaSpoon - Jasmine

I'm trying to write a Javascript spec for my Rails 3.2 application using Teaspoon (the Jasmine version). I'm trying to write a spec that does something like this

describe("Fun", function() {
    var page = require('webpage').create() //ERROR

    it("should be so much fun", function() {
        page.open('/pageToTest/')
        expect($('#HereIsTheParty')).not.toBe( undefined );
    });
});

However, require('webpage') doesn't run (Error: Module name "system" has not been loaded yet for context) even though the Requirejs gem has been installed and can be accessed from the Chrome console.

My question is, can I easily get require('webpage') to run using Rails or should I be using something else? Is it maybe easier to just use Capybara since so far I've been using

describe "Fun", :type => :feature do
    it "should be so much fun" do
        visit '/pageToTest/'
        expect(page).to have_content 'Success'
    end
end

without any problems. I would however prefer using pure Javascript since in this case it's more convenient. What do you guys think? Thanks!


Source: (StackOverflow)

How do I access Rails fixtures from javascript unit tests?

We have done a lot of work testing on the rails side of our application now and are starting to try out unit testing on the javascript side using Teaspoon/Mocha/Sinon/Expectjs.

Now that we are digging deeper we are trying to find the right way to access rails fixture data. For example we want to be able to make a correct api call to (mocked) server with an ActiveRecord model's id number (to call, e.g., /users/:some_id), but these are generated at runtime by the fixture generation.

So far the only way we've gotten this to work is to create a MagicLamp fixture which renders json (instead of, say, a rails partial) and then to call MagicLamp.loadJSON() instead of MagicLamp.load. However this seems like a hacky way to achieve this. Essentially we hoped there'd be a way to have a file like magic_lamp.rb where you can just set up a function similar to the fixture helpers that Rails generates (e.g., users(:name_of_user) for a users.yml file).

I'll admit I may be asking the wrong question here, because it seems like this should be trivial. Maybe we're on the wrong path?


Source: (StackOverflow)

Teaspoon unit test ember notify message with promise

I am testing this code, the syntax is in coffee script.

functionName: ->
    a = @get('content')
    a.on('didUpdate', =>
      @get("controllers.application").notify
            title: "Success!"
            message: "Updated!"
            type: "alert-success"
    )
    a.save()
  1. There's a promise in it, I do not know how to get the .on method, if I stub it out, then the promise will not run...
  2. for the notify, how do I check the assertion? I tried to check the object, but it seems to not be an object with properties.

Source: (StackOverflow)

ember-qunit fails on `expect(4)` claiming to run 5

ember-qunit is claiming to have run 5 assertions, but my test clearly is only making 4 assertions.

Test:

test('setting of properties is bound to model', function() {
  expect(4);

  var controller = this.subject(),
      domain;

  Ember.run(function() {
    domain = Em.Object.create({
      name: 'OG Name',
      domain: 'og.domain.com'
    });
    controller.set('model', domain);
  });

  equal(controller.get('name'), domain.get('name'));
  equal(controller.get('domain'), domain.get('domain'));

  Ember.run(function() {
    controller.setProperties({
      name: 'New Name',
      domain: 'new.domain.com'
    });
  });

  equal(domain.get('name'), 'New Name');
  equal(domain.get('domain'), 'new.domain.com');
});

Failure:

Failures:

  1) Controller - Domain setting of properties is bound to model (1, 5, 6)
     Failure/Error: Expected 4 assertions, but 5 were run

Finished in 12.77100 seconds
160 examples, 1 failure

Any ideas?

Note: I am using teaspoon to run my tests, not sure if that could cause this.


Source: (StackOverflow)