Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactoring module main function, apply minor fixes and added testing suite #7

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules/
assets/screenshot.png
assets/screenshot.png
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ sudo: false
# Keep this in sync with appveyor.yml
node_js:
- '6'
- '7'
- '8'

before_script:
# If this command fails and you can't fix it, file an issue and add an exception to .nsprc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
const path = require("path");
const fs = require("mz/fs");
const linter = require("addons-linter");
const withTmpDir = require("./helpers/tmp-dir");
const cmdRunner = require("./helpers/cmd-runner");
const withTmpDir = require("../helpers/tmp-dir");
const cmdRunner = require("../helpers/cmd-runner");

const execDirPath = path.join(__dirname, "..", "bin");
const execDirPath = path.join(__dirname, "..", "..", "bin");

describe("main", () => {
test("creates files including manifest with correct name", () => withTmpDir(
Expand Down
23 changes: 23 additions & 0 deletions __tests__/unit/errors.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use strict";

const UsageError = require("../../errors").UsageError;
const onlyInstancesOf = require("../../errors").onlyInstancesOf;

describe("onlyInstancesOf", () => {
test("catches specified error", () => {
return Promise.reject(new UsageError("fake usage error"))
.catch(onlyInstancesOf(UsageError, (error) => {
expect(error).toBeInstanceOf(UsageError);
}));
});

test("throws other errors", () => {
return Promise.reject(new Error("fake error"))
.catch(onlyInstancesOf(UsageError, () => {
throw new Error("Unexpectedly caught the wrong error");
}))
.catch((error) => {
expect(error.message).toMatch(/fake error/);
});
});
});
127 changes: 127 additions & 0 deletions __tests__/unit/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"use strict";

const path = require("path");
const fs = require("mz/fs");
const withTmpDir = require("../helpers/tmp-dir");
const UsageError = require("../../errors").UsageError;
const main = require("../../index").main;
const getProjectCreatedMessage =
require("../../index").getProjectCreatedMessage;

describe("main", () => {
test("returns project path and creation message", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);
const dirname = path.join(__dirname, "..", "..");
const expectedMessage = await getProjectCreatedMessage(targetDir, dirname);

const result = await main({
dirPath: projName,
baseDir: tmpPath,
});
expect(result.projectPath).toEqual(targetDir);
expect(result.projectCreatedMessage).toEqual(expectedMessage);
})
);

test("creates files, readme and manifest with correct name", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);

await main({
dirPath: projName,
baseDir: tmpPath,
});

const contentStat = await fs.stat(path.join(targetDir, "content.js"));
expect(contentStat.isFile()).toBeTruthy();

const bgStat = await fs.stat(path.join(targetDir, "background.js"));
expect(bgStat.isFile()).toBeTruthy();

const rmStat = await fs.stat(path.join(targetDir, "README.md"));
expect(rmStat.isFile()).toBeTruthy();

const manifest = await fs.readFile(path.join(targetDir, "manifest.json"), "utf-8");
const parsed = JSON.parse(manifest);
expect(parsed.name).toEqual(projName);
})
);

test("calls all of its necessary dependencies", () => withTmpDir(
async (tmpPath) => {
const projName = "target";

jest.mock("../../dependencies-main");
const mockedDependencies = require("../../dependencies-main");

await main({
dirPath: projName,
baseDir: tmpPath,
deps: mockedDependencies,
});

expect(mockedDependencies.getProjectManifest.mock.calls.length).toBe(1);
expect(mockedDependencies.getProjectManifest.mock.calls[0][0]).toBe(projName);

expect(mockedDependencies.getPlaceholderIcon.mock.calls.length).toBe(1);

expect(mockedDependencies.getProjectReadme.mock.calls.length).toBe(1);
expect(mockedDependencies.getProjectReadme.mock.calls[0][0]).toBe(projName);
})
);

test("throws Usage Error when directory already exists", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);
await fs.mkdir(targetDir);

await expect(main({
dirPath: projName,
baseDir: tmpPath,
})).rejects
.toBeInstanceOf(UsageError);

await expect(main({
dirPath: projName,
baseDir: tmpPath,
})).rejects.toMatchObject({
message: expect.stringMatching(/dir already exists/),
});
})
);

test("throws error when one of dependencies throws", () => withTmpDir(
async (tmpPath) => {
const projName = "target";

jest.mock("../../dependencies-main");

const mockedDependencies = require("../../dependencies-main");

mockedDependencies.getPlaceholderIcon = jest.fn(() => {
throw new Error("unexpected dependency error");
});

await expect(main({
dirPath: projName,
baseDir: tmpPath,
deps: mockedDependencies,
})).rejects.toMatchObject({
message: expect.stringMatching(/unexpected dependency error/),
});
})
);
});

describe("getProjectCreatedMessage", () => {
test("returns message with correct directory", async () => {
const targetDir = path.join("target");
const returnedMessage = await getProjectCreatedMessage(targetDir);

expect(returnedMessage).toMatch(new RegExp(targetDir));
});
});
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ shallow_clone: true
environment:
matrix:
- nodejs_version: '6'
- nodejs_version: '7'
- nodejs_version: '8'

test_script:
- node --version
Expand Down
24 changes: 23 additions & 1 deletion bin/create-webextension
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
#!/usr/bin/env node
const chalk = require("chalk");
const UsageError = require("../errors").UsageError;
const onlyInstancesOf = require("../errors").onlyInstancesOf;

require("..").main();

const USAGE_MSG = `Usage: create-webextension project_dir_name`;

if (!process.argv[2]) {
console.error(`${chalk.red("Missing project dir name.")}\n`);
console.log(USAGE_MSG);
process.exit(1);
}

require("..").main({dirPath: process.argv[2]})
.then(({projectCreatedMessage}) => console.log(projectCreatedMessage))
.catch(onlyInstancesOf(UsageError, (error) => {
console.error(`${chalk.red(error.message)}\n`);
process.exit(1);
}))
.catch((error) => {
// Report the error with its stack trace on unexpected exceptions.
console.error(`${chalk.red(error.message)}: ${error.stack}\n`);
process.exit(1);
});
49 changes: 49 additions & 0 deletions dependencies-main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const path = require("path");
const fs = require("mz/fs");

const README = `
This project contains a blank WebExtension addon, a "white canvas" for your new experiment of
extending and remixing the Web.
`;

exports.getProjectReadme = function getProjectReadme(
projectDirName,
MORE_INFO_MSG
) {
return fs.readFile(path.join(__dirname, "assets", "webextension-logo.ascii"))
.then(() => {
return `# ${projectDirName}\n${README}${MORE_INFO_MSG}`;
});
};

exports.getPlaceholderIcon = function getPlaceholderIcon() {
return fs.readFile(path.join(__dirname, "assets", "icon.png"));
};

exports.getProjectManifest = function getProjectManifest(projectDirName) {
return {
manifest_version: 2,
name: projectDirName,
version: "0.1",
description: `${projectDirName} description`,
content_scripts: [
{
matches: ["https://developer.mozilla.org/*"],
js: ["content.js"],
},
],
permissions: [],
icons: {
"64": "icon.png",
},
browser_action: {
default_title: `${projectDirName} (browserAction)`,
default_icon: {
"64": "icon.png",
},
},
background: {
scripts: ["background.js"],
},
};
};
12 changes: 12 additions & 0 deletions errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const ES6Error = require("es6-error");

exports.onlyInstancesOf = function (errorType, handler) {
return (error) => {
if (error instanceof errorType) {
return handler(error);
}
throw error;
};
};

exports.UsageError = class UsageError extends ES6Error {};
Loading