How to write unit test case using Mocha Chai Sinon of the below scenario? - mocha.js

BankingDocument.findOne({ documentId},
(err, doc) => {
if (err)
throw err;
}
return doc;
}
)

Related

Protractor/Jasmin Stop execution or skip test if BeforeAll or BeforeEach fails

Is there any way to Stop execution or skip test if there are any failures in BeforeAll or BeforeEach ? in Protractor+Jasmin framework
I have tried few things which are not helping like: protractor-fail-fast, jasmine-bail-fast, topSpecOnExpectationFailure: true
In my test if Login does not work in BeforeAll or BeforeEach Test are still getting executed.
Is there any why by which if Login fails it skips the execution in it() blocks.
i think there won't be nice solution here. I can suggest some hack like this:
describe('Some feature', function () {
preconditionFailed = false
beforeAll(async function () {
try {
await somePreconditions()
preconditionFailed = false
} catch(err) {
preconditionFailed = true
throw err
}
}
beforeEach(async function () {
try {
await somePreconditions()
preconditionFailed = false
} catch(err) {
preconditionFailed = true
throw err
}
}
it('should work', async feature() {
if(preconditionFailed) {
throw new Error('Precondition failed, cannot start test')
}
await someTestLogic()
})
})

How to spyOn a function which has an Promise inside and don't return the result but handles the response itself?

How can I spyOn a method called placed in the object?
// Game.js
export default {
mine: null,
handle: function(me) {
console.log(" FOOOOO " + me)
},
setSource: function() {
this.mine.getSource().then((response) => {
const {source} = response
this.handle(source)
})
}
}
Here i try to spy:
// GameSpec.js
import Game from '../../lib/jasmine_examples/Game'
Game.mine = {}
describe("Game", function() {
it("should set source and handle it", function() {
Game.mine.getSource = () => {
return new Promise((resolve)=>{
resolve( {
source : 'BAAAAR'
})
})
}
spyOn(Game, 'handle').and.callThrough()
Game.setSource()
expect(Game.handle).toHaveBeenCalled()
});
});
In the output you can see the function "handle" was called:
Started
F FOOOOO BAAAAR
Failures:
1) Game should set source and handle it
Message:
Expected spy handle to have been called.
Stack:
Error: Expected spy handle to have been called.
at <Jasmine>
at UserContext.<anonymous> (/Users/silverbook/Sites/zTest/jasmine/spec/jasmine_examples/PlayerSpec.js:20:29)
at <Jasmine>
1 spec, 1 failure
But jasmine says it was not called.
If i remove the mocked Promise the test passes but i needed there. In another test i will return an error in the Promise and let it handle from another function.
So the Promise breaks the test but why?
The test executes synchronously and the expect fails before the callback queued by this.mine.getSource().then() has a chance to execute.
For Jasmine >= 2.7 and async function support you can convert your test function into an async function and add an await Promise.resolve(); where you want to pause the synchronous test and let any queued callbacks execute.
For your test it would look like this:
import Game from '../../lib/jasmine_examples/Game'
Game.mine = {}
describe("Game", function() {
it("should set source and handle it", async () => {
Game.mine.getSource = () => {
return new Promise((resolve)=>{
resolve( {
source : 'BAAAAR'
})
})
}
spyOn(Game, 'handle').and.callThrough();
Game.setSource();
await Promise.resolve(); // let the event loop cycle
expect(Game.handle).toHaveBeenCalled();
});
});
For older (>= 2.0) Jasmine versions you can use done() like this:
import Game from '../../lib/jasmine_examples/Game'
Game.mine = {}
describe("Game", function() {
it("should set source and handle it", (done) => {
Game.mine.getSource = () => {
return new Promise((resolve)=>{
resolve( {
source : 'BAAAAR'
})
})
}
spyOn(Game, 'handle').and.callThrough();
Game.setSource();
Promise.resolve().then(() => {
expect(Game.handle).toHaveBeenCalled();
done();
});
});
});
You can run the test inside fakeAsync and run tick() before the expect()
Service:
getFirebaseDoc() {
this.db.firestore.doc('some-doc').get()
.then(this.getFirebaseDocThen)
.catch(this.getFirebaseDocCatch);
}
Unit testing:
it('should call getFirebaseDocThen', fakeAsync(() => { // note `fakeAsync`
spyOn(service, 'getFirebaseDocThen');
spyOn(service.db.firestore, 'doc').and.returnValue({
get: (): any => {
return new Promise((resolve: any, reject: any): any => {
return resolve({ exists: true });
});
},
});
service.getFirebaseDoc();
tick(); // note `tick()`
expect(service.getFirebaseDocThen).toHaveBeenCalled();
}));

Is it possible to send multiple SNS in a lambda function?

I tried to use Promise to do that but always got timeout error. All Going to send logged but no SNS 0 has error or SNS 0 has no error logged
function sendSNSMessage(params, index) {
return new Promise(function (resolve, reject) {
console.log('Going to send', index, params)
sns.publish(params, function(err, data) {
if (err) {
console.log(`SNS ${index} has error: ${err}`)
return reject(err)
}
console.log(`SNS ${index} has no error: ${data}`)
resolve(data)
})
})
}
exports.query = (event, context, callback) => {
const connection = mysql.createConnection(config.db)
try {
connection.connect(function(err) {
if (!err) {
connection.query('SELECT * FROM urls', function(err, results) {
if (!err) {
const messsages = results.map((result, index)=>{
console.log(`results[${index}]: ${result.url}`)
return sendSNSMessage({
Message: result.url,
TopicArn: config.sns.queryArn
}, index)
})
Promise.all(messsages).then(()=>{
callback(null, 'All messages sent')
}, console.error)
} else {
console.log('Query error!')
callback(err)
}
connection.end()
})
} else {
console.log('Error connecting database ...' + err.message)
}
})
} catch (error) {
callback(`Exceptiodn: ${error}`)
}
}
Basically the idea behind is:
Do a mysql query to get a couple of records
Send one SNS per record tp trigger another lambda function

jasmine unit test for modalInstance result

i am new to jasmine tests i could not able to find solution for this after trying in all ways i am posting it here can any body suggest to write test case for this code which is in angular js
modalInstance.result.then(function (modalOutput) {
if (modalOutput) {
if ('okToUndoEdits' === modalOutput[1]) {
$scope.chargebackDetail.cbDetails = angular.copy($scope.chargebackDetailBackup.cbDetails);
} else if ('okToSaveUnmatched' === modalOutput[1]) {
$('#noMatchWarning').show();
$scope.isMatchedDoc = false;
}
}
}, function () {
});

Jasmine 2 custom matcher for hasClass in Protactor

I upgrade my Jasmine 1.3 to 2.0 so I added a custom matcher to check css is present.Below is the code to check the matcher
hasClass = function(actual,expected){
return actual.getAttribute('class').then(function (classes) {
return classes.split(' ').indexOf(expected) !== -1;
});
}
But when I upgrade to Jasmine 2 then promise throws error by protactor as it expect return but below is async process
hasClass = function(){
return compare: function(actual,expected){
return actual.getAttribute('class').then(function (classes) {
return {pass: classes.split(' ').indexOf(expected) !== -1};
});
}
}
How can I test class is present in element I don't want to use jasmine-jquery??
The pass should be a promise, not resolved in one. Try to place this in your beforeEach:
this.addMatchers({
hasClass: function() {
return {
compare: function(actual, expected) {
return {
pass: actual.getAttribute('class').then(function(classes) {
return classes.split(' ').indexOf(expected) !== -1;
})
};
}
};
}
});

Resources