tschaub / mock-fs

Configurable mock for the fs module
https://npmjs.org/package/mock-fs
Other
911 stars 86 forks source link

Mocking uploading files with Needle does not work #244

Open sindilevich opened 6 years ago

sindilevich commented 6 years ago

I am getting Uncaught Error: ENOENT: no such file or directory, open 'C:\Temp\mockFs\fake\base\path\file.png' when trying to mock out uploading files with needle.

System: Windows 7 x64 node.js: 10.8.0 npm: 6.3.0

needle takes file paths and uploads them onto server via HTTP POST. I am setting a file-system mock before using needle.

The file that uses needle:

// poster.ts
import needle from "needle";

export class Poster {
    public async post(file, textFile) {
        const payload = {
            values: {
                Attachment1: file,
                Attachment2: textFile
            }
        };

        return needle("post", "http://localhost:8080/api/files",
            {
                "attach-Attachment1": { file: file, content_type: "image/png" },
                "attach-Attachment2": { file: textFile, content_type: "application/json" },
                "entry": { value: JSON.stringify(payload), content_type: "application/json" }
            },
            { multipart: true });
    }
}

And here is the test suite:

// poster-test.ts
import { expect, use } from "chai";
import chaiAsPromised from "chai-as-promised";
import mockFs from "mock-fs";
import nock from "nock";
import { Poster } from "./poster";

const poster = new Poster();

describe("Poster can...", () => {
    beforeEach("Setup Node.http.request stub and mockFs", () => {
        use(chaiAsPromised);
        mockFs({
            fake: {
                base: {
                    path: {
                        "file.png": "",
                        "file.txt": "This is a textual file"
                    }
                }
            }
        });
    });

    afterEach("Restore after mockFs", () => {
        mockFs.restore();
    });

    it("Succedes to post", async () => {
        nock("http://localhost:8080")
            .post(/^\/api.+/gi)
            .reply(200, (requestBody: string) => console.info(requestBody));
        await poster.post("fake/base/path/file.png", "fake/base/path/file.txt");
    });
});

The test is run with mocha, with extensions by chai.