title: Testing a fs library function with Jest/Typescript
body: <p>I am trying to test a library function that I have written (it works in my code) but cannot get the testing with the mock of the fs to work.  I have a series of functions for working with the OS wrapped in functions so different parts of the application can use the same calls.</p>
  
  <p>I have tried to follow <a href="https://stackoverflow.com/questions/50066138/mock-fs-function-with-jest">this question</a> with mocking the file system, but it does not seem to work for me.</p>
  
  <p>A short sample to demonstrate the basics of my issue are below:</p>
  
  <pre><code>import * as fs from 'fs';
  export function ReadFileContentsSync(PathAndFileName:string):string {
      if (PathAndFileName === undefined || PathAndFileName === null || PathAndFileName.length === 0) {
          throw new Error('Need a Path and File');
      }
      return fs.readFileSync(PathAndFileName).toString();
  }
  </code></pre>
  
  <p>So now I am trying to test this function using Jest:</p>
  
  <pre><code>import { ReadFileContentsSync } from "./read-file-contents-sync";
  const fs = require('fs');
  
  describe('Return Mock data to test the function', () =&gt; {
      it('should return the test data', () =&gt; {
          const TestData:string = 'This is sample Test Data';
  
  // Trying to mock the reading of the file to simply use TestData
          fs.readFileSync = jest.fn();                
          fs.readFileSync.mockReturnValue(TestData);
  
  // Does not need to exist due to mock above     
          const ReadData = ReadFileContentsSync('test-path');
          expect(fs.readFileSync).toHaveBeenCalled();
          expect(ReadData).toBe(TestData);
      });
  });
  </code></pre>
  
  <p>I get an exception that the file does not exist, but I would have expected the actual call to fs.readFileSync to not have been called, but the jest.fn() mock to have been used.</p>
  
  <pre><code>ENOENT: no such file or directory, open 'test-path'
  </code></pre>
  
  <p>I am not sure how to do this mock?</p>