0
votes

I am creating a unit test, this test consists of using the twitter API to obtain data of any profile (Name, number of tweets, followers, date of registration, etc). The point is that I'm using the Mocha library for this task, but I run into the problem, that when executing the assert, the twitter request takes more than 2 seconds (Mocha's default timeout), therefore my test always fails. Could someone give me a hand? What should I do, so that the comparison of the assert is executed after receiving all the data of the request to twitter?

code.js

class extractCode {
    verificarUsername(a) {
        if (a) {
            var nombre;
            var Twitter = require('twitter');
            var client = new Twitter({
              consumer_key: 'XSpj4nEB5IOLgIvyZXiDAhBLt',
              consumer_secret: 'dPjYUTih6n0ynt1y9C7bE0g0gyx6KSJgrGTeDEa3yH5flsdJPL',
              access_token_key: '900532686-4sOwDfOFZm1fKmtZZhSMPH04REXMjqnugTOn3o1j',
              access_token_secret: 'ghNtHt7VyjwNHXvXnZM5hFKaDH62bX7LEFqUBZ9SSb5Lg'
            });

            client.get('users/show', {screen_name: a}, function(error, response) {
              if(error) throw error;
              if(response.name) {
                nombre = true
              } else {
                nombre = false
              };
              console.log(` 
                Nombre: '${response.name}'
                ID: ${response.id_str}
                Localidad: ${response.location}
                Descripción del perfil: ${response.description}
                Seguidores: ${response.followers_count}
                Sigue a: ${response.friends_count}
                Perfil creado el: ${response.created_at}\n`);
            });
            return nombre;
        }


    }
}

module.exports = extractCode;

test/prueba.js

var assert = require('assert');
var extractCode = require('../code.js');

describe('Pruebas de perfil de Twitter', function() {
    this.timeout(5000);
    var c = new extractCode();
    it('Verifica si se le pasó un username válido', function(done) {

            assert.equal(c.verificarUsername('pedrofumero'),true, 'El username proporcionado no es válido');
            done();



    })

})
1

1 Answers

1
votes

your test and code is wrong and probably 5s its not really an timeout value when testing third party api requests. I've had requests to other third party apis take more than an minute(s) to respond.

here is an basic approach rewriting your code with promises

test.js

var assert = require('assert');
var extractCode = require('./code.js');
describe('Twitter profile', function() {
    it('Twitter username verification, expect an actual response', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            //console.log(response)
            done()
        })
        .catch(function(err){
          throw err;
        });
    })
    it('Twitter username verification, expect an error response', function(done) {
        var c = new extractCode();
        c.verificarUsername('')
        .then(function(response){
            //console.log(response)
            //assert.equal(response.verified,true,'Valid username');
        })
        .catch(function(err){
          assert.equal(err[0].message,'User not found.');
          done()
        });
    })
    it('Twitter username verification, expect an verified profile', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            assert.equal(response.verified,true,'Valid username');
            done();
        })
        .catch(function(err){
          done(err);
        });
    })
})

code.js

var Twitter = require('twitter');
var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});
class extractCode {
    verificarUsername(Username) {
        return client.get('users/show', {   screen_name: Username })
    }
}
module.exports = extractCode;

output

Twitter profile                                                     
  √ Twitter username verification, expect an actual response (610ms)
  √ Twitter username verification, expect an error response (391ms) 
  1) Twitter username verification, expect an verified profile      


2 passing (1s)                                                      
1 failing                                                           

1) Twitter profile                                                  
     Twitter username verification, expect an verified profile:     

    AssertionError [ERR_ASSERTION]: Valid username                  
    + expected - actual                                             

    -false                                                          
    +true                                                           

    at test.js:32:11                                                
    at <anonymous>                                                  
    at process._tickCallback (internal/process/next_tick.js:188:7)