0

I'm trying to write a test with jasmine for a typescript method that reads a file and processes it. This method has two steps (outside of reading the file): validating the file and then processing it. I want to test that the method throws an exception when the file is invalid.

For my tests, I need example files to test, so I was wondering what the best practice to generate/store representative test files is. Should I create these by hand and save them with the tests? Should I write something that generates files to test? Write something that generates file data to test? Something else entirely?

From other questions (Unit Testing File I/O) I can see that I don't need to test the I/O itself, just the method's functionality, but I do need some data to test the method with.

MattB
  • 159
  • 2
  • 8

1 Answers1

0

As you describe, what you want to test is that the content of the files is properly validated. File content is just data, and for the validation procedure it should not make a difference where the data actually came from. That means, the "file content" could also be provided as data that in fact is provided directly from the test code:

  • In the simplest case the data could just be constant strings or byte arrays.
  • If it gets a bit more complex you could have some test helper methods that create the data.
  • You might even consider using the actual component that is responsible for creating the data if that does not violate any of your testing goals.

This requires that you are able to bypass the reading of the file content in some way, for example by mocking the file access operations. Or, by separating the reading of the file from the validation of the content such that the validation part already gets some in-memory data to validate and can be tested separately.

Whether your scenario allows to go this way is not clear from your question. If it is possible, however, it has some nice properties: Your tests are easier to maintain, because you are not dealing with a number of files but have everything in one place (namely the file with the tests). You are less dependent on file system issues like lack of write or read access, case sensitivity of file names and the like.

Dirk Herrmann
  • 5,550
  • 1
  • 21
  • 47