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)
})

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay