1

I have an Angular application that can parse files from user input. I need to run Jasmine/Karma unit tests in my browser to verify the parsing is working correctly.

Obviously I cannot just read the file with fs.readFileSync since this is not running in Node. Is there any way to load files similar to this, perhaps to load them into Jasmine/Karma memory before the tests are run?

Currently I have to copy the contents of my files into strings in mock typescript objects. This is a lot of silly duplication since the actually file is right here beside it. Plus, this does not work for binary files since copying the file contents as a string doesn't play well.

Here's what I'm doing currently:

mock-files.ts

const encoder = new TextEncoder();
function createBuffer(str: string) {
  return encoder.encode(str).buffer;
}

export const mockSongShowPlusFile1: IRawDataFile = {
  name: 'Be Near',
  ext: 'sbsong',
  type: '',
  dataAsBuffer: createBuffer(`&\u0000\u0000...`), //long binary string here, but it doesn't work
  dataAsString: ``, //For other file types I'd paste the raw content as a string here
};

test.spec.ts

import { mockSongShowPlusFile1 } from 'mock-files';

it('should return a song for a SongShow Plus 7 file1', () => {
  const testFile: IRawDataFile = structuredClone(mockSongShowPlusFile1);

  expect(inputConverter.extractSongData(testFile)).toEqual({
    fileName: testFile.name,
    title: 'Be Near',
    info: [
      { name: 'Author', value: 'Barnard, Shane' },
      { name: 'Copyright', value: '2003 Waiting Room Music' },
      { name: 'CCLI', value: '4090362' },
      { name: 'Key', value: 'B' },
    ],
    slides: [ ... ], //actual array data would go here
  });
});

How can I get this binary file data into my unit tests?

Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • I haven't done this before but maybe you can use the `files` property of `karma.conf.js`. Check out the following: https://stackoverflow.com/a/20942898/7365461 and here is the documentation of `karma`'s files property: http://karma-runner.github.io/6.4/config/files.html. I want to say that the solution should be in `karma` (if it exists) since it is the test runner and not in `jasmine` since it is a testing framework. – AliF50 Sep 01 '23 at 13:04
  • Interesting, that actually partially works! I can add those files to karma, but when I try to load then with `require('/path/to/file.sbsong')` I get the Karma error: *"You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file)"* – Chris Barr Sep 02 '23 at 13:50
  • I've made a new question that's more specific with these new findings now: https://stackoverflow.com/questions/77028605/how-can-i-load-binary-files-in-a-jasmine-karma-test – Chris Barr Sep 02 '23 at 20:06

0 Answers0