unit testing express route with async callback

unit testing express route with async callback

Content Index :

unit testing express route with async callback
Tag : node.js , By : user171752
Date : November 23 2020, 01:01 AM

wish help you to fix your issue if you are using mocha it provides the "done" function that you can inject into your callback and it will tell mocha that test is async and should wait until that function is called
it('should do something',function(done){

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Unit testing promise based code in node.js express route/controller

Tag : node.js , By : CyberGreg
Date : March 29 2020, 07:55 AM
With these it helps If your method being tested doesn't return a promise then you can't use the promise syntax in Mocha. You can test your method the same way you'd test any other asynchronous method - with done as a parameter of it. Let's say we want to test your handler function:
var handler =  function (req, res, next) {
  User.findAsync(query, null, options).then(function (user) {
  }).catch(function (e) {
describe("The handler", function(){
     it("calls res.json", function(done){ // note the done argument
         handler({query: {before: 5}, // mock request
                 {json: done} // res.json calls our `done` param of this function
                 function(){ throw new Error("error called"); });

Async callback was not invoked within timeout - Unit testing a Typescript & Angular $http service

Tag : angularjs , By : Shrek Qian
Date : March 29 2020, 07:55 AM
This might help you After translation to JavaScript it will be look like this (as $httpBackend.flush() runs digest loop internally) I have also extract query params to object to stop DRY violation
  .module('app', [])
  .service('orderSearchService', function($http) {
    this.search = function(term) {
      return $http.get("http://testUrl" + "/api/search/" + term).success(function(data) {
        return data;

describe('orderSearchService', function() {
  var $httpBackend, orderSearchService;


  beforeEach(inject(function(_$httpBackend_, _orderSearchService_) {
    $httpBackend = _$httpBackend_;
    orderSearchService = _orderSearchService_;

  it("can call $http and retrieve results", function() {
    var query = {
      q: 'testquery',
      response: 'testData'

    $httpBackend.whenGET(new RegExp('http://testUrl/api/search/' + query.q)).respond(200, query.response);

    orderSearchService.search(query.q).then(function(promise) {
      var results = promise.data;
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

Unit testing express route callback - mock res object

Tag : javascript , By : cthulhup
Date : March 29 2020, 07:55 AM
I wish this helpful for you The reason you're getting this error should be clear in that you don't have a view engine set on your Express application when attempting to run the render() method.
From the Express documentation on template engines (obviously replace the below with the engine you're using in your application):
app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine

Unit testing async function with callback

Tag : javascript , By : John R
Date : March 29 2020, 07:55 AM
I hope this helps . Trying to write unit tests for reading a json file with the readFile function however I get the error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout. I must be doing something wrong when mocking the json file. , You're trying to use your functions synchronously?
jest.mock('fs', () => {
  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
  return {
    readFile: (fpath, callback) => {
      if (fpath in MOCK_FILE_INFO) {
        callback(null, MOCK_FILE_INFO[fpath]);
function jsonReader(filePath, cb) {
  fs.readFile(filePath, (err, fileData) => {
    if (err) {
      return cb && cb(err);
    try {
      const object = JSON.parse(fileData);
    } catch (err) {
      return cb && cb(err);
module.exports = jsonReader;

Java unit testing - how to unit test an async method (uses callback) with mockito answer

Tag : java , By : Mark W
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Port forwarding not working for Nodejs application
  • Dialogflow: throw new Error(`@grpc/grpc-js only works on Node ${supportedNodeVersions}`)
  • In new React version, how to fix TypeError: styled_components__WEBPACK_IMPORTED_MODULE_3__.default.dev?
  • How to add delay before/during test (using supertest & jest) while waiting for dynamodb event to occur
  • change JSON.stringify to what?
  • CosmosDB MongoDB adapter projection not working
  • Express router calls the wrong route
  • How to join table that contains no data yet with sqlite
  • How to filter by string parameter , web3 2.0.0-alpha.1 Solidity events?
  • How to find document.activeElement in Puppeteer
  • Postgresql JSONB | nested arrays gives ERROR aggregate function calls cannot be nested
  • 404 error when deploying angular sample app in production mode
  • Setting up environment variable in nodeJs
  • How to get the view definition in SQL server using NodeJS through code
  • how to give user specific file access in express js
  • passwordHash field in admin.auth.UserRecord interface of Firebase Admin SDK
  • Mongoose get updated document after instance.update()
  • how to extract JWT when authorize in Nestjs
  • Will buying a non sleep dyno on Heroku allow me to upload files without loosing them?
  • Why Pug isn't showing any message when I do res.redirect after req.flash?
  • insert node_modules assets into my project
  • Mongoose - Why might model.find() trigger JSON TypeError in basic server?
  • where is the GET/POST syntax in this code?
  • How to fix 'Failed at the est-ggjr@0.1.0 start script'-error
  • Nodejs server on my PC not receiving POST request from AWS instance
  • Errors with running code that works on another computer
  • How to correctly send HTTPS request to Server using auto-generated SSL keys?
  • how do I maintain time offsets in moment?
  • add a value for the status parameter?
  • Calling C function from returned pointer in NodeJS
  • Using Node.js on StackBlitz?
  • Export multiple modules from NPM package
  • Where and when to use Firebase admin.app().delete()?
  • Why node.js always says I'm connected to my MongoDB even if the "URI" is fake or wrong?
  • Postgresql jsonb -> invalid reference to FROM-clause entry for table "mt"
  • How can I send Apollo Server errors to Sentry?
  • Design pattern to solve event mess in Electron apps with ipcMain and ipcRenderer
  • What im doing wrong?
  • Why do I get a UserCodeSyntaxError when I have no syntax error in my code?
  • I am getting the following error while creating the ember application through cmd
  • TSLoader + Babel Polyfill : You may need an additional loader to handle the result of these loaders while running npm ru
  • i can't receive any answer from Watson Discovery
  • How to get hash value from image using ImageMagick or GraphicsMagick Node.js?
  • How to require dotenv/config file on (before) PM2 starts
  • Node JS Async/Await
  • How to concat chunks of incoming binary into video (webm) file node js?
  • GitLab CI with Postgres ERROR: connect ECONNREFUSED
  • Is it possible to show live data from MongoDB via socket.io?
  • Uploading HDR photo from iPhone to web - GPS data missing
  • Can I run multiple node version on Jenkins?
  • How to set default boolean value in sequelize
  • Cannot read property 'db' of null javascript with parcel
  • using async function into loop with nodejs?
  • How to use keycloak with NestJS properly
  • Changing the title of the header
  • How can i make an horizontal carousel in dialogflow?
  • how to fix the problem when i run any command regarding to npm it shows error
  • node.js - how to check/get ssl certificate expiry date
  • How to show base64 image in react?
  • Error while pushing to Heroku: Cannot find module 'node-linux-x64/package.json'
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com