how to use qunit and promise to test my function? - promise

I have two function:
test.set(object details)
test.onChanged.addListener(function(object info) {...})
fired onChanged when a test is set.
So, how should I use qunit and promise to test it?
QUnit.asyncTest("onChanged with set", function(assert) {
new Promise(function(r1) {
test.set({});
r1();
}).then(function() {
new Promise(function(r2) {
test.onChanged.addListener(function(info) {
assert.ok(true, "onChanged callback");
assert.deepEqual(info, {}, "onChanged result");
r2();
});
});
}).then(function() {
QUnit.start();
});
});
But, it does not run.

Related

Chai http Promise never failing

I am using Chai http and the promise. The following test should fail, but it passes without ever calling the then function. If I add the done parameter to wait for the async function to finish, it fails (correctly). Am I doing something wrong?
it('Returns the correct amount of events', function() {
chai.request(app)
.get('/api/events/count')
.then(function(res) {
throw new Error('why no throw?');
expect(res).to.have.status(200);
expect(res).to.be.json;
})
.catch(function(err) {
throw err;
});
});
When you forget to return promise your test is evergreen. So, you just need to return promise to make it work:
it('Returns the correct amount of events', function() {
return chai.request(app)
.get('/api/events/count')
.then(function(res) {
throw new Error('why no throw?');
expect(res).to.have.status(200);
expect(res).to.be.json;
})
.catch(function(err) {
return Promise.reject(err);
});
});

How to use superagent when testing in Jest-CLI?

I need to fetch some real data in my tests from a remote url. I Superagent is not being mocked. I have done that by including node_modules/superagent/ in unmockedModulePathPatterns.
This is the file I am trying to test, the .end() function is never called.
This is my test, which fails with a timeout error.
jest.dontMock("../Stocks.js");
jest.dontMock("superagent");
describe("Stock Actions", () => {
var makeRequest = require('../Stocks')
pit("doesn't crash", function () {
var promise = makeRequest("Hello World")
promise.then(function (str) {
expect(str).toBe("yay");
});
return promise;
});
});
And this is the module it's trying to test:
import Reflux from 'reflux';
import request from 'superagent';
console.log("request-superagent", request)
const makeRequest = Reflux.createAction({ asyncResult: true });
const Store = Reflux.createStore({
init() {
this.listenTo(makeRequest, 'onMakeRequest');
},
onMakeRequest(url) {
request('GET', 'http://api.example.com/list/')
.end(function (err, res) {
console.log("res.text", res.text);
if (!res.ok) {
makeRequest.failed("aw");
}
makeRequest.completed("yay");
});
}
});
module.exports = makeRequest;
How do I use superagent in jest-cli?

testing ui-router stateprovider 'resolve:' values

I'm using jasmine+karma to run the following code...
and get the following error:
Expected { then : Function, catch : Function, finally : Function } to equal 123.
Can someone help me understand why I don't get a resolved value for my promise. thanks
'use strict';
angular
.module('example', ['ui.router'])
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
url: '/stateOne',
resolve: {cb: function($q) {
var deferred = $q.defer();
deferred.resolve(123);
return deferred.promise;
}},
controller: function($scope, cb) {console.log(' * in controller', cb);},
templateUrl: 'stateOne.html'
});
})
.run(function($templateCache) {
$templateCache.put('stateOne.html', 'This is the content of the template');
});
describe('main tests', function() {
beforeEach(function() {module('example');});
describe('basic test', function($rootScope) {
it('stateOne', inject(function($rootScope, $state, $injector, $compile) {
var config = $state.get('stateOne');
expect(config.url).toEqual('/stateOne');
$compile('<div ui-view/>')($rootScope);
$rootScope.$digest();
expect($injector.invoke(config.resolve.cb)).toEqual(123);
}));
});
});
Ok, Figured it out with some help (via email) from Nikas, whose blog I found at:
http://nikas.praninskas.com/angular/2014/09/27/unit-testing-ui-router-configuration/.
Here is a succinct example that demonstrates how to test the resolve values in ui.router, where the values involve $http.
angular
.module('example', ['ui.router'])
.factory('Clipboard', function($http) {
return {
get: function(args) {
return $http.get('/db/clipboard');
}
};
})
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
resolve: {cb: function(Clipboard) {
return Clipboard.get();
}}
});
});
describe('main tests', function() {
beforeEach(function() {module('example');});
it('stateOne', inject(function($state, $injector, $httpBackend) {
$httpBackend.whenGET('/db/clipboard').respond({a:1});
$injector.invoke($state.get('stateOne').resolve['cb'])
.then(function(res) {console.log(' *res ', res.data);})
.catch(function(err) {console.log(' *err ', err);});
$httpBackend.flush();
}));
afterEach(inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
});

Mocha doesn't fail on assert(false)

When using mocha to test a model of a sails app, It doesn't seem to run tests inside a callback:
var assert = require('assert');
describe('Dataset', function() {
describe('create', function() {
it('should create a new dataset', function() {
Dataset.create({
'name': 'testDataSet',
'description': 'This dataset exists for testing purposes only.',
'visibility': 'private',
'data': {
"foo": {
"barn": "door",
"color": "green"
}
}
}, function(err, dataset) {
assert(false);
});
});
});
});
This test is called by a script that initializes sails for it.
when Running this test, it passes, even though it should fail.
$: mocha
1 passing (875ms)
Also it never seems to run the callback containing assert(false). Placing assert false at any other location yields the exepcted results, also sails seems to be running properly.
Any help is greatly appreciated.
Your code is asynchronous, so you should use callback in your testing function:
var assert = require('assert');
describe('Dataset', function() {
describe('create', function() {
it('should create a new dataset', function(done) {
Dataset.create({
'name': 'testDataSet',
'description': 'This dataset exists for testing purposes only.',
'visibility': 'private',
'data': {
"foo": {
"barn": "door",
"color": "green"
}
}
}, function(err, dataset) {
if (err) throw err;
done();
});
});
});
});
Add assert call wherever you need.
There are a lot of examples here.

Jasmine calling function with ajax returned value

I want to test the "addGroup" function using Jasmine. I get the following error:
Error: Expected spy modifyMyHtml to have been called.at null.
I don't know what is the best way to test the addGroup function. Please HELP.....
var myRecord = {
addGroup: function(groupNumber) {
$.when(myRecord.getHtml())
.done(function(returnedHtml){
myRecord.modifyMyHtml(returnedHtml);
});
},
getHtml: function() {
return $.ajax({url: "myHtmlFile.html", dataType: "html" });
},
// adds options and events to my returned HTML
modifyMyHtml: function(returnedHtml) {
$('#outerDiv').html(returnedHtml);
var myOptions = myRecord.getOptions();
$('#optionsField').append(myOptions);
myRecord.bindEventsToDiv();
},
}
====JASMINE TEST
describe("Configure Record page", function() {
var fixture;
jasmine.getFixtures().fixturesPath = "/test/" ;
jasmine.getFixtures().load("myHtmlFile.html");
fixture = $("#jasmine-fixtures").html();
describe("addGroup", function(){
beforeEach(function() {
var groupNumber = 0;
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().promise();
});
spyOn(myRecord, "modifyMyHtml");
myRecord.addGroup(groupNumber);
});
it("Should call getHtml", function() {
expect(myRecord.getHtml).toHaveBeenCalled();
});
it("Should call modifyMyHtml", function() {
expect(myRecord.modifyMyHtml).toHaveBeenCalled(); ==>FAILS
});
});
});
You have to resolve the promise before you return em in your andCallFake.
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolve ().promise();
});
Btw. you should not test that the function on the object you wanna test are called, but that the html in the DOM are set with the right html
it("Should call modifyMyHtml", function() {
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolveWith(null, 'returnedHtml').promise();
});
expect($('#outerDiv').html).toEqual('returnedHtml')
});

Resources