jeremyfa / yaml.js

Standalone JavaScript YAML 1.2 Parser & Encoder. Works under node.js and all major browsers. Also brings command line YAML/JSON conversion tools.
MIT License
889 stars 142 forks source link

NetworkError when I use in jest unit test #103

Open Pasupathi-Rajamanickam opened 6 years ago

Pasupathi-Rajamanickam commented 6 years ago

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 commented 6 years ago

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

jeremyfa commented 6 years ago

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 commented 6 years ago

104

enbock commented 6 years ago

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