9

I am working on a text generator and I would like to compare the generated string with a text stored in a sample files. Files have indentation for some lines and it is very cumbersome to construct these strings in TS/js

Is there a simple way to load text from folder relative to current test or even project root in Jest?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Jar
  • 591
  • 1
  • 5
  • 5

2 Answers2

10

Try this to import your txt into the jest file then compare with it:

const fs = require("fs");
const path = require("path");

const file = path.join(__dirname, "./", "bla.txt");
const fdr = fs.readFileSync(file, "utf8", function(err: any, data: any) {
  return data;
});

expect(string).toBe(fdr)
-1

Next to simply loading the text from a file as @avshalom showed in Jest you can also use snapshots to compare your generator output with files.

It's as simple as

it('renders correctly', () => {
  const text = myGenerator.generate({...});
  expect(text).toMatchSnapshot();
});

On first run the snapshot files will be written by Jest. (You then usually checkin those snapshots files) As far as i know you won't have much control over the location of the snapshot files or how to structure multiple files (other than splitting your tests across multiple test files).

If you want more control over how the files are stored and split, checkout jest-file-snapshot.

oae
  • 1,513
  • 1
  • 17
  • 23