jeudi 18 juin 2020

while loop in the tested function executing only once in Jest

When I try to call a method, the while loop in the method executes only once instead of the given 5 times. Is there a solution to this?

//mock.js

const TestModel = require('src/models/testModel')

const mockFunction = async (id) => {
    let i = 0
    while(i < 5){
        console.log(i)
        const response = await calledFunction(id)
        return response
        i = i + 1
    }
}

const calledFunction = async(id) => {
    console.log(id)
    const testModels = await TestModel.findById({ id })
    return testModels
}
module.exports = {
    mockFunction
}

And this is my test

//mock.test.js

const mongoose = require('mongoose')

const { mockFunction } = require('./mock')
const TestModel = require('src/models/testModel')

jest.setTimeout(75000);

TestModel.findById = jest.fn()

TestModel.findById = jest.fn().mockReturnValue({
    _id: '5dbff32e367a343830cd2f49',
    name: 'Label',
    __v: 0
})

test('mock test', async () => {
    mockFunction(new mongoose.Types.ObjectId())
        .then(function (result) {
            console.log(result)
        })
})

I have used mocks here to return a mock response and I don't have any problem with it. The while loop should supposedly execute 5 times in the above case but the test stops once it executes just once. Is there a problem with the test? Should I change mock.js or mock.test.js?

I'm a newbie in node.js and any help would be appreciated. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire