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

Add codemode for importing sinon #9

Open
tarjei opened this issue Feb 9, 2018 · 1 comment
Open

Add codemode for importing sinon #9

tarjei opened this issue Feb 9, 2018 · 1 comment

Comments

@tarjei
Copy link

tarjei commented Feb 9, 2018

(I originally suggested this codemod here: skovhus/jest-codemods#53)
I do not have time to write a PR but you might want to add something like this:

/**
 * A quick code mod to move from using a sinon global to using sinon 2.x with an import statement.
 */

// findImports, hasRequireOrImport stolen from
// https://github.com/skovhus/jest-codemods/blob/master/src/utils/imports.js

function findImports (j, ast, pkg) {
  return ast.find(j.ImportDeclaration, {
    source: {
      value: pkg
    }
  })
}
/**
 * Detects CommonJS and import statements for the given package.
 * @return true if import were found, else false
 */
function hasRequireOrImport (j, ast, pkg) {
  // const requires = findRequires(j, ast, pkg).size()
  const imports = findImports(j, ast, pkg).size()
  return imports > 0
}

function hasIdentifier (j, ast, name) {
  return ast.find(j.Identifier, {
    name
  }).size() > 0
}

module.exports = function (fileInfo, api) {
  const j = api.jscodeshift
  const ast = j(fileInfo.source)

  if (!hasRequireOrImport(j, ast, 'sinon') && hasIdentifier(j, ast, 'sinon')) {
    let imp = ast.find(j.ImportDeclaration, {})
    // console.log(imp)

    let node = imp.at(imp.size() - 1)

    const {statement} = j.template
    // const newNode = j.importDeclaration('sinon', 'sinon');
    node.insertAfter(statement`import sinon from 'sinon'`)

    return node.toSource()
  }
}
@hurrymaplelad
Copy link
Owner

Thanks for sharing! PR welcome from anyone who wants to pick this up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants