2

I have this Jest test that calls an async function called getLD which is itself an async function:

test("Should generate correct lexical density", async () => {
    var ld = await getLD("John is a Smith")
    console.log(ld);
    expect(ld).toEqual('Paul');
    expect.assertions(1);
})

And this is the async function it calls:

const NonLexWord = require('../models/Word');
exports.getLD = async (sentence) => {
    const nonLexicalWords = await NonLexWord.find({});
    // console.log(nonLexicalWords);
    const words = sentence.split(" ");
    const totalNumberOfWords = words.length;
    let totalNumberOfLexicalWords = 0;
    words.forEach(word => {
        const found = nonLexicalWords.find(element => element.name === word);
        if(!found) {
            totalNumberOfLexicalWords++;
        }
    });
    return parseFloat((totalNumberOfLexicalWords / totalNumberOfWords).toFixed(2));
}

My issue is that the body of the test never runs and I receive this error:

: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

This is the Word model:

// For non lexical words
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const WordSchema = new Schema({
    name: {
        type: String,
    }
});

module.exports = Word = mongoose.model('word', WordSchema);

Of Course I did try increasing the time threshold like this.

Seif
  • 701
  • 4
  • 13
  • 32
  • How is `NonLexWord.find()` defined? – Patrick Roberts Jan 21 '20 at 15:13
  • @PatrickRoberts I just edited the question with the definition. It's a mongoose Schema model. – Seif Jan 21 '20 at 15:16
  • There is no mystery about this when the Async routine is called it is synchronous for that instant in that each line is processed one after the other. If it encounters another asynchronous call then you are just adding the call. – SPlatten Jan 21 '20 at 15:28
  • Are you sure the function you are calling is finishing before the timeout? Does it just run longer than 5000ms? – Jared Smith Jan 21 '20 at 15:29
  • @JaredSmith This function is used for an endpoint and it takes far less than 5000ms even though it runs several times. So yes. – Seif Jan 21 '20 at 15:30
  • only for testing purpose give more time to jest , put this row jest.setTimeout(60000) at the beginning of the test. – Andrea Bisello Jan 21 '20 at 17:31
  • Unit test or integration test? Do your test cases depend on a real MongoDB server? – Lin Du Jan 22 '20 at 03:57

0 Answers0