yaml.js icon indicating copy to clipboard operation
yaml.js copied to clipboard

NetworkError when I use in jest unit test

Open Pasupathi-Rajamanickam opened this issue 8 years ago • 4 comments

I'm trying to write backend test cases attached with yml, when the yml file tries to load, getting NetworkError The reason behind this is, jest having window object with the execution so ymljs trying to access file using xhr how to solve this issue?

Pasupathi-Rajamanickam avatar Dec 11 '17 17:12 Pasupathi-Rajamanickam

I did window.XMLHttpRequest = false; on top of my test. But need a better way to solve this problem

Pasupathi-Rajamanickam avatar Dec 11 '17 18:12 Pasupathi-Rajamanickam

You don't have to use yaml.load() actually. You could just fetch the raw yaml data yourself in whichever way you want (like, with fs.readFile() in node?) and parse it with yaml.parse(). That should give you more control

jeremyfa avatar Dec 11 '17 21:12 jeremyfa

#104

jeremyfa avatar Dec 12 '17 12:12 jeremyfa

You can just mock the whole YamlJs:

jest.mock(
  'yamljs',
  function createYamlJsMock() {
    return {parse: jest.fn()};
  }
);
import YAML from 'yamljs';

describe('Foo', function testFoo() {

  it('Bar', function testBar() {
   (new MyYamlReader())->loadAndParse("dummy"); 
    // call in MyYamlReader class: YAML.parse
    expect(YAML.parse).toHaveBeenCalled();

    YAML.parse.mockReset(); // reset, because kinda global mocked ;)
  });
});

enbock avatar Feb 01 '18 19:02 enbock