Skip to content

Commit

Permalink
fix(require-module): Support scope within a required module
Browse files Browse the repository at this point in the history
Prior release did not recognize the scope of a required module. The following is now supported
'const bar = require("foo").bar;'

closes #12
  • Loading branch information
schempy committed Feb 4, 2018
1 parent b3474bb commit 279cc64
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 43 deletions.
34 changes: 34 additions & 0 deletions __tests__/unit/mocks.spec.js
Expand Up @@ -615,5 +615,39 @@ describe("Mocks", () => {

expect(output).toBe(expected);
});

test("should not mock a scope on a required module", () => {
const code = `
const someFunction = require("util").someFunction;
function doSomething() {
someFunction();
}
module.exports = doSomething;
`;

const output = generateCode({
code: code,
testFramework: "jest",
filename: "my-module.js",
removeWhitespace: true
});

const expected = `
const someFunction = require("util").someFunction;
const doSomething = require("my-module");
describe("my-module.js", () => {
test("doSomething", () => {
doSomething();
});
});`
.replace(/ /g, "")
.trim();

expect(output).toBe(expected);
});
});
});
22 changes: 12 additions & 10 deletions index.js
Expand Up @@ -9,7 +9,9 @@ const mkdirp = require("mkdirp");
const globby = require("globby");

function getOptions(opts) {
const defaultTestFramework = opts["test-framework"] ? opts["test-framework"] : "jest";
const defaultTestFramework = opts["test-framework"]
? opts["test-framework"]
: "jest";

return {
testFramework: defaultTestFramework
Expand All @@ -25,15 +27,14 @@ function eachFilename(patterns, callback) {
.map(filePath => path.relative(process.cwd(), filePath));

if (filePaths.length === 0) {
console.error(`No matching files. Tried: ${patterns.join(" ")}`)
console.error(`No matching files. Tried: ${patterns.join(" ")}`);
process.exitCode = 2;
return;
}

filePaths.forEach((filePath) => {
filePaths.forEach(filePath => {
callback(filePath);
})

});
} catch (err) {
console.error(`Unable to expand glob patterns: ${patterns.join(" ")}`);
process.exitCode = 2;
Expand Down Expand Up @@ -84,15 +85,14 @@ function parseOptions(opts) {
];

process.stdout.write(usage.join("\n"));
}
else {
} else {
generate(opts);
}
}

function generate(opts) {
const filepatterns = opts["_"];

eachFilename(filepatterns, filename => {
const options = getOptions(opts);

Expand All @@ -101,14 +101,16 @@ function generate(opts) {
try {
const input = fs.readFileSync(filename, "utf8");
const testfile = generateTestFileName(filename);
createTestDirectory(testfile);
createTestDirectory(testfile);
const ast = parser.parse(input);
const astModel = modelUtil.generate(ast, filename);
const output = testUtil.generate(astModel, options);

fs.writeFileSync(testfile, output, "utf8");
} catch (err) {
console.error("Unable to write test file: " + filename + "\n" + err + "\n");
console.error(
"Unable to write test file: " + filename + "\n" + err + "\n"
);
process.exitCode = 2;

return;
Expand Down
2 changes: 1 addition & 1 deletion src/cli.js
Expand Up @@ -3,7 +3,7 @@ const platelunch = require("../index");

function run(args) {
const opts = minimist(args);

platelunch.parseOptions(opts);
}

Expand Down
22 changes: 16 additions & 6 deletions src/model-util.js
Expand Up @@ -41,7 +41,7 @@ function generate(ast, filename) {

CallExpression(path) {
if (t.isIdentifier(path.node.callee, { name: "require" })) {
requireDeclarations.push(path.parent);
requireDeclarations.push(path.parentPath);
}
},

Expand Down Expand Up @@ -85,11 +85,21 @@ function generate(ast, filename) {
});
});

requireDeclarations.forEach(ast => {
testModel.addRequireDeclaration({
name: ast.id.name,
path: ast.init.arguments[0].value
});
requireDeclarations.forEach(parentPath => {
let name = "";
let path = "";
let scope = "";

if (t.isMemberExpression(parentPath.node)) {
name = parentPath.parent.id.name;
path = parentPath.node.object.arguments[0].value;
scope = parentPath.node.property.name;
} else {
name = parentPath.node.id.name;
path = parentPath.node.init.arguments[0].value;
}

testModel.addRequireDeclaration({ name, path, scope });
});

if (classBodies.length > 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/test-framework.js
Expand Up @@ -4,7 +4,7 @@ const frameworks = {
get jest() {
// eslint-disable-next-line no-eval
return eval("require")("./test-framework/jest");
},
}
};

function getBuilder(opts) {
Expand Down
2 changes: 1 addition & 1 deletion src/test-framework/jest.js
Expand Up @@ -178,7 +178,7 @@ jestUtil.preTest = function(opts) {

const thisExpFilter = callExpression.filter(callExp => callExp === this);
let callCanBeSpied = true;

// Method/function can be spied if there is a object and method
// Example: someLibrary.someMethod()
if (thisExpFilter.length === 0 && callExpression.length === 1) {
Expand Down
50 changes: 26 additions & 24 deletions src/test-util.js
Expand Up @@ -37,9 +37,7 @@ function generate(model, opts) {
function createMainFileInclude(opts) {
const regEx = RegExp(/\w+\.js/g);
const fileExtMatch = regEx.test(opts.filename);
const filename = fileExtMatch
? opts.filename.split(".")[0]
: opts.filename;
const filename = fileExtMatch ? opts.filename.split(".")[0] : opts.filename;

const exportDeclarations = opts.exportDeclarations;
const moduleExports = opts.moduleExports;
Expand All @@ -48,7 +46,7 @@ function createMainFileInclude(opts) {
if (exportDeclarations.length > 0) {
const specifiers = exportDeclarations.reduce((acc, exportDeclaration) => {
let specifier = null;

if (exportDeclaration.type === "named") {
specifier = t.importSpecifier(
t.identifier(exportDeclaration.name),
Expand All @@ -59,17 +57,13 @@ function createMainFileInclude(opts) {
t.identifier(exportDeclaration.name)
);
}

acc.push(specifier);

return acc;
}, []);

sourceFiles = [t.importDeclaration(
specifiers,
t.stringLiteral(filename)
)];

sourceFiles = [t.importDeclaration(specifiers, t.stringLiteral(filename))];
} else {
sourceFiles = moduleExports.reduce((acc, moduleExport) => {
if (moduleExport.type === "identifier") {
Expand All @@ -78,13 +72,16 @@ function createMainFileInclude(opts) {
);
} else {
acc.push(
template.ast(`const ${moduleExport.value} = require("${filename}").${moduleExport.value};`)
template.ast(
`const ${moduleExport.value} = require("${filename}").${
moduleExport.value
};`
)
);
}

return acc;
}, []);

}

return sourceFiles;
Expand Down Expand Up @@ -435,16 +432,21 @@ function createRequireDeclarations(opts) {
const requireDeclarations = opts.requireDeclarations;
const requireDeclarationsAst = requireDeclarations.reduce(
(acc, requiredModule) => {
const requireStatement = t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(requiredModule.name),
t.callExpression(t.identifier("require"), [
t.stringLiteral(requiredModule.path)
])
)
]);

acc.push(requireStatement);
if (requiredModule.scope) {
acc.push(
template.ast(
`const ${requiredModule.name} = require("${requiredModule.path}").${
requiredModule.scope
};`
)
);
} else {
acc.push(
template.ast(
`const ${requiredModule.name} = require("${requiredModule.path}");`
)
);
}

return acc;
},
Expand Down

0 comments on commit 279cc64

Please sign in to comment.