0
votes

I have stubbed the content of file, so I can run through only outer function

file.html

<body onload ="test('file.txt')">
<body>

file.js

    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         test1,
         param
    }

    function test (outputParam) {
      let fileData = test1(outputParam);
      param = fileData;
    }

    function test1(outputParam) {
       let data = fs1.readFileSync(outputParam);
       return data; 
    }

Here as you see I load function test from html onload and in turn test1 calls and reads file, I have stubbed this file content as shown in the test below

When I run the test I want to see the variable param has the file content value

test.spec.js

    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function' ,function() {

    // I try to stub my function here
    sinon.stub(filejs,'test1').callsFake ((someArg) => {
      return "this is my file content";
    });

        // Now I will call my test function
        filejs.test(someArg);

    })

As you seen above I have stubbed function test1, still when I run the test I see test1 gets called and it reads the real file.

I am using mocha , I am new to stub or mock concepts, any suggestion is really appreciated.

1
Let me know If you did not understand my question - karansys
sinon.stub() can only affect the properties of the export object but the test() function calls the internal function test1() directly. sinon.stub() can’t do anything about the internals of a module. - Lennholm

1 Answers

1
votes

You should probably try to stub readFileSync.

const fs = require('fs');

// ...

sinon.stub(fs, "readFileSync").callsFake ((someArg) => {
  return "this is my file content";
});

Besides that, I can spot two issues with your code.

  • The real readFileSync will return a Buffer if called without a second parameter, not a string like your stub does.

  • The body onload event only exists inside the DOM. The fs module is only available in Node.js. If you run your code in a browser, you won't be able to use fs.readFileSync. If you run it in Node, your HTML file and the onload event won't be useful.