Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves - mocha.js

I have tried to insert the value in db in my mocha test i am getting this error i tried few of the following ways but nothing work out.
var assert=require('chai').assert;
const user=require('../model/user')
i tried both way
describe('insertDataLasone',()=>{
it('should save the value ',(done)=>{
var User = new user({fname:'test'});
User.save().then(done=>{
done()
}).catch(done=>done())
})
})
describe('User', function() {
describe('#save()', function() {
// this.timeout(5000)
it('should save without error', function(done) {
var User5 = new user({fname:'test'});
User5.save(function(done) {
if (err) done(err);
else setTimeout(done,3000);
});
});
});
});

This error occurs when done() is not called in a test. Make sure you are calling done().
var assert = require('chai').assert;
const User = require('../model/user');
describe('insertDataLasone', () => {
it('should save the value ', done => {
var user = new User({ fname: 'test' });
user.save().then(() => {
done();
})
.catch(done); // mocha done accepts Error instance
});
});
or
var assert = require('chai').assert;
const User = require('../model/user');
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user5 = new User({ fname: 'test' });
user5.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
Read https://mochajs.org/#asynchronous-code carefully

Related

Not able to use alias across tests in Cypress

I am trying to create a framework for API tests using cypress and I am facing an issue accessing the data between tests using an alias. Is there something that I am missing?
custom.js
Cypress.Commands.add('getResource', function (uri) {
cy.request({
url: uri,
method: 'GET'
}).then(function (response) {
return cy.wrap(response);
});
});
test.js
exports.__esModule = true;
context('requests', function () {
it('validate get call response', function () {
let re = cy.getResource('https://reqres.in/api/users?page=2','resp')
re.then(function (response) {
cy.wrap(response.body).as('respbody');
cy.wrap(response.status).as('respstatus');
//cy.log(JSON.stringify(response.body));
});
});
it('Tests test', function () {
cy.wait('#respbody').then((body) => {
console.log(JSON.stringify(body));
});
});
});
cypress version - 8.2.0
By design cypress cleans up aliases after each test. So you can do something like this cypress recipe
Your getResource custom command is taking just one parameter, hence we are passing just one papameter.
exports.__esModule = true;
let responseBody;
let responseStatus;
context('requests', () => {
before(() => {
cy.getResource('https://reqres.in/api/users?page=2')
.then(function(response) {
responseBody = response.body
responseStatus = response.status
})
})
beforeEach(() => {
cy.wrap(responseBody).as('responseBody')
cy.wrap(responseStatus).as('responseStatus')
})
it('Get Response status', function() {
cy.wait('#responseStatus').then((responseStatus) => {
console.log(responseStatus)
})
})
it('Get Response Body', function() {
cy.wait('#responseBody').then((responseBody) => {
console.log(JSON.stringify(responseBody))
})
})
})

Unable to pass parameter from the api request to outside

The code below is a simple mocha test where I am trying to pass the value of the variable my_token so that I can use in different tests. Tried all the possibilities but its not working. Not sure what I am doing wrong!
var supertest = require('supertest'),
api = supertest('www.xyz.com');
var my_token = 'DID NOT WORK';
describe('get collars list', function(done) {
before(function(done) {
api.post('/api/v2/auth')
.send({username:"SP",password:"**"})
.set('Content-Type', 'application/json')
.expect(200)
.end(function (err, res) {
my_token = "worked"
done();
});
console.log ('passing value to the test : '+ my_token );
});
it('should login', function(done) {
console.log (' token passed to test : ' + my_token);
});
});
You do not need done in a test case that doesn't involve asynchronous operation.
This should work.
var supertest = require("supertest"),
api = supertest("www.xyz.com");
var my_token = "DID NOT WORK";
describe("get collars list", function(done) {
before(function(done) {
api
.post("/api/v2/auth")
.send({ username: "SP", password: "**" })
.set("Content-Type", "application/json")
.expect(200)
.end(function(err, res) {
my_token = "worked";
done();
});
console.log("passing value to the test : " + my_token);
});
it("should login", function() {
console.log(" token passed to test : " + my_token);
});
});

mocha chaijs : $ is not defined

I'm trying to setting up automated test.
I'm using zombiejs for the browser, mochaJs for the test framework and chaiJs for assertion. I want to use chai-jq for jquery assertion:
var expect = require('chai').expect
var chai = require("chai");
var chaiJq = require('chai-jq');
Browser = require('zombie'),
browser = new Browser();
chai.use(chaiJq);
describe('Test', function(){
before(function(done) {
browser.visit('http://localhost/login.php', done);
});
describe('Connexion au site', function() {
before(function(done) {
browser
.fill('login', 'foo')
.fill('password', 'bar')
.pressButton('Connexion', done);
});
it('should be successful (code 200)', function() {
browser.assert.success(200);
});
});
describe('', function() {
browser.visit('http://localhost/activites/nationales/accueil.php');
it('contain text', function() {
var $elem = $("<div id=\"hi\" foo=\"bar time\" />");
expect($elem)
// Assertion object is `$elem`
.to.have.$attr("id", "hi").and
// Assertion object is still `$elem`
.to.contain.$attr("foo", "bar");
});
});
When I run the test i've got the error ReferenceError: $ is not defined

Mocha multiple test in order

Mocha multiple test in order
I am writting test with mocha like this
describe('application', function(){
describe('First set of test', function(){
var socket;
before(function(done) {
var opts = {
'reconnection delay' : 0,
'reopen delay' : 0,
'forceNew' : true
};
socketio = io.connect(SOCKET_URL, opts);
done();
socketio.on('connect', function() {
console.log('worked...');
});
socketio.on('disconnect', function() {
console.log('disconnected...');
})
});
it('first test should be true', function(done){
expect(variable_one).to.be.false;
done();
});
it('second test should be true', function(done){
client.hget(hash, "status", function(err, result){
expect(variable_two).to.be.true;
done();
})
});
it('thrid test should be true', function(done){
client.hget(hash, "status", function(err, result){
expect(variable_three).to.be.true;
done();
})
});
});
});
What I need is that test should be nested in order, to set the before variables is not enough because the third test depends on the second and the second on the first one. With the done variable are all running in parallel.
Is there a posible way to achieve this?
Thank you

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