I’m trying to build a wrapper around Stackblitz’s web containers for my documentation. I’m using a javaScript class for this:
import {WebContainer, FileSystemTree} from "@webcontainer/api";
import fs from "fs";
import path from "path";
import {fileURLToPath} from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default class Container {
private mContainer!: WebContainer;
constructor() {
this.CreateContainer();
this.ScaffoldViteApp();
this.StartDevServer();
}
private CreateContainer = async () => {
try {
this.mContainer = await WebContainer.boot();
} catch (err) {
throw new Error(JSON.stringify(err));
}
return this.mContainer;
};
private ScaffoldViteApp = async () => {
try {
this.mContainer.spawn("npm", [
"create",
"vite",
"container-example -- --template react-swc-ts"
]);
} catch (err) {
throw new Error(JSON.stringify(err));
}
return this.mContainer;
};
private StartDevServer = async () => {
try {
this.mContainer.spawn("npm", ["run", "dev"]);
} catch (err) {
throw new Error(JSON.stringify(err));
}
return this.mContainer;
};
public SetComponent(name: string) {
const files: FileSystemTree = {
"Component.tsx": {
file: {
contents: fs.readFileSync(
path.join(
__dirname,
"../../apps/components",
name.toLowerCase(),
`${name.charAt(0).toUpperCase()}${name.slice(1)}.tsx`
)
)
}
}
};
try {
this.mContainer.fs.mkdir("components");
} catch (err) {
throw new Error(JSON.stringify(err));
}
try {
this.mContainer.mount(files, {mountPoint: "components"});
} catch (err) {
throw new Error(JSON.stringify(err));
}
return this.mContainer;
}
public GetIframe() {
return this.mContainer.on("server-ready", (port, url) => {
return url;
});
}
public WriteComponent(name: string, content: string) {
const files: FileSystemTree = {
"Component.tsx": {
file: {
contents: content
}
}
};
try {
this.mContainer.mount(files, {mountPoint: "components"});
} catch (err) {
throw new Error(JSON.stringify(err));
}
return this.mContainer;
}
}
And I’m testing it with Vitest:
import Container from "../createContainer";
import {it, describe, expect, vi, beforeEach} from "vitest";
describe("CreateContainer", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("should create a container with a basic vite project when the class is initialized", () => {
const container = new Container();
});
it("should load a specified component into the container", () => {
const container = new Container();
container.SetComponent("example");
});
it("should return the url to the container's iframe", () => {
const container = new Container();
container.GetIframe();
});
it("should write changes to the component on the container", () => {
const container = new Container();
container.WriteComponent("example", "console.log('Hello World')");
});
});
However, all of my test are failing with no message just {}
. What could be causing this? I’m trying to mock the window before each test but still the same errors occur.