DEV Community

Randy
Randy

Posted on

2 1

Using file-test to test your generated file

When we write a program that will generate some files, how do we test this kind of program? I always use the fs module, test if the directories or files are existed. But I need to write many boring codes for this.

So I write file-test, for the test cases that care about the generated.

Suppose I wrote a program that should generate this directory structure:

- root
  - readme.md
  - A
    - a.js
    - b.js
  - B
    - a.ts 
    - b.ts

With file-test, I can simply test it like:

const FileTest = require('file-test')

const ft = new FileTest(path.resolve(__dirname, './root'))

ft.includeFile('readme.md') // => true
ft.includeFile('blabla.md') // => false
ft.includeFile('A/a.js') // => true
ft.includeFile('A/b.js') // => true

ft.readFile('A/a.js') // => console.log('hello js')

ft.includeDirectory('A') // => true
ft.includeDirectory('B') // => true
ft.includeDirectory('A/a.js') // => false

ft.include([
  'readme.md',
  'A/a.js',
  'B/a.ts',
]) // => true

ft.include([
  'readme.md',
  'A/a.ts',
  'B/a.ts',
]) // => false

It is easy to use with Jest too:

test('directory structure', () => {
  expect(ft.includeDirectory('B')).toBe(true)
  expect(ft.includeDirectory('A/a.js')).toBe(false)
  expect(ft.readFile('A/a.js')).toEqual(`console.log('hello js')`)
  expect(ft.include([
    'readme.md',
    'A/a.js',
    'B/a.ts',
  ])).toBe(true)
})

Image of Bright Data

Maintain Seamless Data Collection – No more rotating IPs or server bans.

Avoid detection with our dynamic IP solutions. Perfect for continuous data scraping without interruptions.

Avoid Detection

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay