lundi 10 février 2020

How to test recursive function in Jest.js

I have an script to looping over directories and match files with specific type. Unfortunately jest passes this test before it ends. I know why, but I don't know how to make script to wait for the end of looping.

import fs from 'fs'
const path = require('path');

describe('something', () => {
    it('should something', () => {
        const traverseDir = (dir, callback) => {
            fs.readdirSync(dir).forEach(file => {
                let fullPath = path.join(dir, file);
                if (fs.lstatSync(fullPath).isDirectory()) {
                    callback(fullPath)
                    traverseDir(fullPath, callback);
                } else {
                    callback(fullPath)
                }
            });
        }

        traverseDir('src/', (fullPath) => {
            const splitted = fullPath.split('/')
            const filename = splitted[splitted.length - 1]
            if (filename.match(/.*.foo/)) {
                fs.readFile(fullPath, 'utf8', (err, data) => {
                    expect(err).toBe(null)
                    // some assertion
                })
            }
        })
    })
})

Aucun commentaire:

Enregistrer un commentaire