Mocha error cannot find module

I'm using babeljs to write an RPG engine library. I have two files: dice.js import assert from 'assert'; import Random from 'random-js'; export default class Dice { constructor(maxNumber) {

I’m using babeljs to write an RPG engine library. I have two files:

dice.js

import assert from 'assert';
import Random from 'random-js';

export default class Dice {
  constructor(maxNumber) {
    assert(typeof(maxNumber) === "number", "maxNumber must be a number");

    this._mt = Random.engines.mt19937();
    this.minNumber = 1;
    this.maxNumber = maxNumber;
  }

  makeThrow() {
    this._mt.autoSeed();
    return Random.integer(this.minNumber, this.maxNumber)(this._mt);
  }
}

throwManager.js

import assert from 'assert';
import Dice from 'dice';
export default class ThrowManager {
  constructor(settings) {
    assert(settings.hasOwnProperty("numberOfDices"), "must set 'numberOfDices'");
    assert(settings.hasOwnProperty("maxNumberInDice"), "must set 'maxNumberInDice'");
    assert(settings.maxNumberInDice <= 1, "must have at least 1 dice");
    this.settings = settings;
  }
  execute() {
    var throwResults = [];
    for (var d = 1; d <= this.settings.numberOfDices; d++) {
      var dice = new Dice(this.settings.maxNumberInDice);
      throwResults.push(dice.makeThrow());
    };
    return throwResults;
  }
}

When I test them with mocha, I do these imports:

tests.js

var assert = require('assert');
var Amzhen = require('../Amzhen.js');
var random = require('random-js');
//tests here...

Yet when I run the tests, I get this:


Error: Cannot find module 'dice'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/Amzhen.js:47:28)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/test/tests.js:2:14)

Any ideas why the dice module isn’t being found?

I’m compiling the code with babel src --out-file Amzhen.js && mocha

I’m using babeljs to write an RPG engine library. I have two files:

dice.js

import assert from 'assert';
import Random from 'random-js';

export default class Dice {
  constructor(maxNumber) {
    assert(typeof(maxNumber) === "number", "maxNumber must be a number");

    this._mt = Random.engines.mt19937();
    this.minNumber = 1;
    this.maxNumber = maxNumber;
  }

  makeThrow() {
    this._mt.autoSeed();
    return Random.integer(this.minNumber, this.maxNumber)(this._mt);
  }
}

throwManager.js

import assert from 'assert';
import Dice from 'dice';
export default class ThrowManager {
  constructor(settings) {
    assert(settings.hasOwnProperty("numberOfDices"), "must set 'numberOfDices'");
    assert(settings.hasOwnProperty("maxNumberInDice"), "must set 'maxNumberInDice'");
    assert(settings.maxNumberInDice <= 1, "must have at least 1 dice");
    this.settings = settings;
  }
  execute() {
    var throwResults = [];
    for (var d = 1; d <= this.settings.numberOfDices; d++) {
      var dice = new Dice(this.settings.maxNumberInDice);
      throwResults.push(dice.makeThrow());
    };
    return throwResults;
  }
}

When I test them with mocha, I do these imports:

tests.js

var assert = require('assert');
var Amzhen = require('../Amzhen.js');
var random = require('random-js');
//tests here...

Yet when I run the tests, I get this:


Error: Cannot find module 'dice'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/Amzhen.js:47:28)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/test/tests.js:2:14)

Any ideas why the dice module isn’t being found?

I’m compiling the code with babel src --out-file Amzhen.js && mocha

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

Comments

@EliasJorgensen

Hi,

I’m using v3.2.0 of the generator for my project, but when i run grunt i get the following error:

Running "env:test" (env) task
Loading "mocha-test.js" tasks...ERROR
>> Error: Cannot find module 'mocha'
Warning: Task "mochaTest:unit" failed. Use --force to continue.

Aborted due to warnings.

I’m running the LTS version of node, and npm v2.14.7

@EliasJorgensen

I don’t know if it’s any help, but i’m getting these warnings when the generator runs npm install:

npm WARN peerDependencies The peer dependency mocha@>=1.20.0 included from grunt-mocha-test will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency 
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
npm WARN deprecated lodash@0.9.2: lodash@<2.0.0 is no longer maintained. Upgrade to lodash@^3.0.0
npm WARN deprecated lodash@1.0.2: lodash@<2.0.0 is no longer maintained. Upgrade to lodash@^3.0.0
npm WARN deprecated CSSselect@0.7.0: the module is now available as 'css-select'
npm WARN optional dep failed, continuing fsevents@1.0.6
npm WARN optional dep failed, continuing fsevents@1.0.6
npm WARN deprecated CSSwhat@0.4.7: the module is now available as 'css-what'
npm WARN peerDependencies The peer dependency kerberos@~0.0 included from mongodb-core will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency 
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.

@JRhyne

I had the same issue earlier.

Try running
npm install mocha

@EliasJorgensen

That changed the error to this:

Running "mochaTest:unit" (mochaTest) task
Warning: Cannot find module './modules/es5' Use --force to continue.

Aborted due to warnings.

The weird part is that i chose Jasmine for testing, and not mocha…?

@EliasJorgensen

I get the same error when running grunt serve, but with express instead of mocha:

Running "express:dev" (express) task
Starting background Express server
Debugger listening on port 5858
module.js:340
    throw err;
    ^

Error: Cannot find module './modules/es5'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:289:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/vagrant/node_modules/babel-core/node_modules/core-js/shim.js:1:63)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)
Stopping Express server

@EliasJorgensen

I’m only getting this error when choosing Jasmine.
Everything runs fine when choosing Mocha…

@JRhyne

I’m not sure then =/

What version of node.js and npm are you using?

@EliasJorgensen

I’m running Node v4.2.4 and npm v2.14.7

@Awk34

What OS are you on? I’ve seen the Error: Cannot find module './modules/es5' issue on TravisCI, but Codeship didn’t have that problem. There must be some bug in the generator..

@EliasJorgensen

I’m running an Ubuntu 14.04 vagrant box, so everything should be nice and stable on the OS side… =/

@Awk34

It’s probably not a stability thing, but more of an environment issue. Do you think you could copy your code to another OS and see if the issue is fixed? Trying to narrow down the issue..

@EliasJorgensen

I have Arch running on my laptop.. I could try running it on that?

@Awk34

Sure, worth a shot. I just want to see if it behaves the same on a different OS.

@EliasJorgensen

Alrighty then. I’ll reproduce my steps and post the results when i’m done :)

@EliasJorgensen

I had no issues on Arch.
Here is my terminal output: http://pastebin.com/u5Rx6mxN

I was using a cleanly generated project on this AND in my previous posts.
So we can exclude that factor from the problems.

@vucalur

same issue, but @JRhyne ‘s solution works for me.

mocha is not included as an dependency to any package in package.json.
Shouldn’t it be listed in package.json ?

@Awk34

@vucalur

my bad.
Please check the surrounding ifs then.
When jasmine is chosen, mocha is not included in generated package.json. I guess mocha package should be present for both jasmine and mocha choices.

As per different behaviour on different OSes: Check if you have mocha installed globally. That could be the reason why it’s working.

@EliasJorgensen

I don’t have Mocha installed globablly, no.

@Awk34

@vucalur ah, that’s right, since we don’t have the option for using Jasmine for server tests

@LuckyLin

@EliasJorgensen I also have the problem with «Cannot find module ‘mocah'»

Maybe you can try
npm install —save-dev karma-mocha

Hope it helps

@EliasJorgensen

This issue is a year old, so i do not have this issue anymore.
Thanks for trying to help out though, maybe someone in the future will find it helpful 😄

@eduardfrankford

For me: npm install -g mocha solved the issue

Содержание

  1. Error: Cannot find module ‘./options’ #2582
  2. Comments
  3. Error: Cannot find module ‘mocha’ #1532
  4. Comments
  5. Error: Cannot find module ‘./options’ (fresh start) #2423
  6. Comments

Error: Cannot find module ‘./options’ #2582

when starting mocha the recommended way:

I get the following error:

the error goes away if I start mocha via:

Here some system info:

The text was updated successfully, but these errors were encountered:

What do you get from the following commands?

  • npm bin
  • ./node_modules/.bin/mocha
  • npm test (with «test»: «mocha» in the «scripts» entry in package.json )

npm bin yields the path to the .bin dir inside the node_modules dir of the app: [. ]app/node_modules/.bin

./node_modules/.bin/mocha gives the error which I posted above:

npm test with «test»: «mocha» gives the same error.

Note that mocha is not installed as global package, it is only a dev dependency of the package and installing it globally is not an option.

Hmm. What if you uninstall Mocha and reinstall it, as in #2423?

Note that mocha is not installed as global package, it is only a dev dependency of the package and installing it globally is not an option.

Yeah, we don’t recommend global installs anyway. They interfere with local installs and cause confusion as to which version of Mocha is being run.

Actually the hint form #2423 did work. After calling:

running tests via $(npm bin)/mocha works. Unfortunately, I have no idea why.

If you can figure out what triggers the options module to go missing in the first place, please let us know.

I had the exact same problem. I found that my global mocha install worked correctly, but there was some kind of problem with my local install of mocha.

  • I ran npm test it gave the above ‘./options’ error.
  • I ran mocha it worked.
  • I changed into the local node_modules directory and ran mocha it gave the same ‘./options’ error appdir/node_modules/.bin/mocha

I resolved, by deleting ‘mocha’ and ‘_mocha’ from my appdir/node_modules/.bin directory.
npm test now runs the global version of mocha and works as expected.

I commented on the other issue #2423 ( my comment ) with some suggested fixes. Just wanted to let you know @ScottFreeCode

I’m have the exact same issue. Can See the option file is there in the mocha bin folder still the error was coming.

/Dropbox/Web DeveLopment/node_authentication$ cd node_modules/mocha/bin/ greenarrow@Anku:

/Dropbox/Web DeveLopment/node_authentication/node_modules/mocha/bin$ ls mocha _mocha options.js greenarrow@Anku:

/Dropbox/Web DeveLopment/node_authentication/node_modules/mocha/bin$ ls -ltr total 36 -rw-rw-r— 1 greenarrow greenarrow 710 Oct 24 2016 options.js -rwxrwxr-x 1 greenarrow greenarrow 12575 Apr 24 14:16 _mocha -rwxrwxr-x 1 greenarrow greenarrow 2179 Apr 24 14:16 mocha greenarrow@Anku:

I uninstalled it completely from local and there was no global mocha install, too on my system. Cleared npm cache too.

Further even after uninstall the mocha and _mocha was there in the bin directory of node_modules. Which should not be there after uninstall.

Seems like mocha var getOptions = require(‘./options’); here is trying to load the ./options from current directory bin itself.

Checking the long listing shows _mocha and mocha in .bin was present as regular file.

After running npm install mocha again can see now symlink instead of the regular file and the test is running fine.

Both Mocha version is same for above case mocha version «mocha»: «^3.3.0»

So i Tried checking in the old test that was written on some other system by other guys and saw there too it was the same regular file and it was not symlink and it too was throwing the same error when i ran it using npm test .

mocha package.json has following at gthub

Current install created Symlink and earlier there was regular file.

After doing cd node_modules/.bin of my project and rm mocha _mocha , the error vanished.

Note: I also ensured I had mocha installed globally.

Further even after uninstall the mocha and _mocha was there in the bin directory of node_modules. Which should not be there after uninstall.

I’d like to point out that this particular detail is an NPM issue rather than a Mocha issue, as Mocha does not control the removal of symlinks or scripts from node_modules/.bin .

After doing cd node_modules/.bin of my project and rm mocha _mocha , the error vanished.

Note: I also ensured I had mocha installed globally.

You removed the entry point of the local install and used the global install instead. However, we don’t recommend using a global install of Mocha in the first place (there’s no significant benefit known to us at this time — even in this case, reinstalling the local copy should suffice instead — and there is non-negligible risk that it will result in use of an outdated Mocha version and/or confusion as to which version of Mocha is actually being used). Also, deleting the files from node_modules/.bin instead of uninstalling and/or reinstalling Mocha will basically leave it half installed, and I don’t know the possible effects of that.

I’ve had the chance to confirm that this issue can result from using rsync with options that convert symlinks into regular files (and therefore, by extension, anything else that does the same). I’ve been thinking about how to address it.

So far I haven’t come up with anything I think is a good idea. I’ve thought of a fairly wide variety of bad ones. Potential solutions vary in robustness, in helpfulness and in the assumptions they make about the package manager that’s installing Mocha; I haven’t come up with any that are more than marginally helpful, are robust and don’t make any assumptions.

One thing that has crossed my mind is that this potentially affects any (especially locally installed) CLI Node program (excepting Windows-only ones, if there even are any of those). Mocha might get hit by it more than others due to greater popularity, but to really resolve the issue in general you’d have to either have every Node CLI program handle this in some way or else change NPM’s use of symlinks. So I wonder: is there some expected convention that other programs follow and Mocha just happens to be out of the ordinary for missing it? Or is this something that arguably ought to be fixed in NPM instead of every CLI program having to come up with a way to handle it?

Источник

Error: Cannot find module ‘mocha’ #1532

I’m using v3.2.0 of the generator for my project, but when i run grunt i get the following error:

I’m running the LTS version of node, and npm v2.14.7

The text was updated successfully, but these errors were encountered:

I don’t know if it’s any help, but i’m getting these warnings when the generator runs npm install :

I had the same issue earlier.

Try running
npm install mocha

That changed the error to this:

The weird part is that i chose Jasmine for testing, and not mocha.

I get the same error when running grunt serve , but with express instead of mocha:

I’m only getting this error when choosing Jasmine.
Everything runs fine when choosing Mocha.

I’m not sure then =/

What version of node.js and npm are you using?

I’m running Node v4.2.4 and npm v2.14.7

What OS are you on? I’ve seen the Error: Cannot find module ‘./modules/es5’ issue on TravisCI, but Codeship didn’t have that problem. There must be some bug in the generator..

I’m running an Ubuntu 14.04 vagrant box, so everything should be nice and stable on the OS side. =/

It’s probably not a stability thing, but more of an environment issue. Do you think you could copy your code to another OS and see if the issue is fixed? Trying to narrow down the issue..

I have Arch running on my laptop.. I could try running it on that?

Sure, worth a shot. I just want to see if it behaves the same on a different OS.

Alrighty then. I’ll reproduce my steps and post the results when i’m done 🙂

I had no issues on Arch.
Here is my terminal output: http://pastebin.com/u5Rx6mxN

I was using a cleanly generated project on this AND in my previous posts.
So we can exclude that factor from the problems.

same issue, but @JRhyne ‘s solution works for me.

mocha is not included as an dependency to any package in package.json .
Shouldn’t it be listed in package.json ?

my bad.
Please check the surrounding if s then.
When jasmine is chosen, mocha is not included in generated package.json . I guess mocha package should be present for both jasmine and mocha choices.

As per different behaviour on different OSes: Check if you have mocha installed globally. That could be the reason why it’s working.

I don’t have Mocha installed globablly, no.

@vucalur ah, that’s right, since we don’t have the option for using Jasmine for server tests

Источник

Error: Cannot find module ‘./options’ (fresh start) #2423

Trying to create a simple test app from scratch. When executing from CLI, receive this error. If I downgrade to 2.5.3 then all is fine. Trying either of the commands below, error.

The text was updated successfully, but these errors were encountered:

I have tried to reproduce this with the current npm version and failed. 😑

I’m wondering if you see anything any differences between my scenario and yours, and maybe that would point us what could be wrong here. 🤓

@gurdiga Hey there. I will perform the exact same tasks here to see what happens. I know I have done this before reporting, but I will start a new project again and record as you have done so we can compare. Thx for taking the time to do this, something is surely interfering?

@gurdiga of course, when I follow this approach from scratch, all works. I will see if I can track down the issue in my current project. This for efforts, will close for now but if I can reproduce, I will reopen this ticket.

I also encountered that issue several times without understand the origin of the problem. By the way, I deleteed the /node_modules folder and npm install to fix it.

@damienromito I have experienced this issue soooooo many times with Mocha 3.x, it is just routine to perform

Anytime it occurs. I have had success skipping the uninstall action and just reinstall Mocha, but that has not helped 100% of the time. So I just run mocha-install alias and move

and then move on as it fixes it for the time being

If anyone can figure out what triggers the options module to go missing in the first place, please let us know.

@ScottFreeCode I have spent quite some time trying to track it down with zero success. I have had it happen quite often, but haven’t been able to find the root cause. Certainly happens frequently enough to warrant an alias reinstall when it occurs 🙁

I have a repo sync’d via dropbox on two computers (because.. well.. don’t ask). The new sync gets this error while the old sync does not. If I run npm uninstall -D mocha && npm i -D mocha on the new computer, it fixes that computer. However, it busts the old one back to this issue. This isn’t blocking me so I’m not gonna throw myself at it too hard, but I have a stable repro if anyone wants me to do some tests/checks.

I had done a npm install on a new project and ran into this issue when doing npm test.

Suggested workaround of removing node_modules directory and doing npm install again worked for me.

@jervisfm I receive this issue randomly (never taken the to really debug it much).

However, it happens frequently enough that I created an alias

I just run this whenever I see the error message

I regularly experience this when I copy and paste a node_modules folder or move it from one place to another. Something in mocha is hardcoded so that when you move the node_modules folder mocha stops working until you uninstall and reinstall mocha.

Pretty bad design imho.

Can we get done data here so we can track it down?

Node version, npm version, mocha version, operating system

@nathanpeck since you seem to have a consistent reproduction, could you create a test case or help us out with some more details?

I believe this may be due to spaces on the path.

I can run mocha by running npm uni -D mocha && npm i -D mocha and then npm test but it will always fail the following execution with that error

@Munter FWIW, I have not seen this happen in quite some time. So many variables have changed since then, hard to say what the «real» cause has been.

@Munter If I am able to reproduce, I will let you know. I am doing a lot of testing at the moment on a current project, thus I would expect at some point for this to happen again.

Oh, I should have mentioned that.

I’m using mocha 3.2.0 and node 6.7.0.

I encountered this issue when I was running npm install on one machine, making a zip file of all my code and node_modules, and then unzipping the file on another machine. The process of making the zip file turned the symlink at node_modules/.bin/mocha into a regular file, so that when it was installed on the second machine, it would look for ./options in node_modules/.bin instead of in node_modules/mocha/bin .

I fixed the issue by running zip —symlinks to preserve the link from node_modules/.bin/mocha -> ../mocha/bin/mocha

I’m not too familiar with the internals of mocha, but one potential fix would be to move the code in ./options to mocha/bin/mocha (and mocha/bin/_mocha ) so that there isn’t a relative import in bin/mocha .

The above fix would duplicate the code in ./options , so if that is undesirable, the «node way» would be to make it a separate module and include the new module as a dependency.

I think I had the same issue, related to @sierranevadan ‘s, excepting that I Rsync’d my whole app structure to a VM guest.

Regardless, I encountered this issue, nuked my local node_modules/ and ran yarn install (npm analogue). After reinstalling everything mocha works as I expect.

mocha 3.2.0, node v6.10.1, yarn 0.21.3

The issue with Symlinks is definitely causing the issue updated the detailed here.
#2582 (comment)

I’m not too familiar with the internals of mocha, but one potential fix would be to move the code in ./options to mocha/bin/mocha (and mocha/bin/_mocha ) so that there isn’t a relative import in bin/mocha .

Where this is caused by the symlinks having been transformed into regular files (the only confirmed cause so far that I’m aware of), it would just error on the next relative import — it’s not actually the options module that’s at fault, but rather the fact that the files have effectively been transferred to and are running from the wrong location.

I’ve had the chance to confirm that this issue can result from using rsync with options that convert symlinks into regular files (and therefore, by extension, anything else that does the same). I’ve been thinking about how to address it.

So far I haven’t come up with anything I think is a good idea. I’ve thought of a fairly wide variety of bad ones. Potential solutions vary in robustness, in helpfulness and in the assumptions they make about the package manager that’s installing Mocha; I haven’t come up with any that are more than marginally helpful, are robust and don’t make any assumptions.

One thing that has crossed my mind is that this potentially affects any (especially locally installed) CLI Node program (excepting Windows-only ones, if there even are any of those). Mocha might get hit by it more than others due to greater popularity, but to really resolve the issue in general you’d have to either have every Node CLI program handle this in some way or else change NPM’s use of symlinks. So I wonder: is there some expected convention that other programs follow and Mocha just happens to be out of the ordinary for missing it? Or is this something that arguably ought to be fixed in NPM instead of every CLI program having to come up with a way to handle it?

I have even stranger behaviour. I have a project where I use script section of package.json to define my test command. This looks like the below

This works absolutely fine. Then I started working on a new project where I have exactly the same setup but kept getting this error to do with missing options module. I first checked if the node_modules/.bin contains a file named options or options.js . Both projects do not have this file and still, one project does not complain and other complains.

I changed the test script of the complaining project to explicitly point to mocha in node_modules/.bin folder by changing the script to the below

Then I noticed that the mocha install directory node_modules/mocha has a bin directory that contains a options.js file. So I changed my script to refer to mocha from there like the below

This makes the error go away. But I am not sure why the first project still works without any options file in nide_modules/.bin directoy.

@schatekar NPM creates node_modules/.bin/mocha as a symlink to node_modules/mocha/bin/mocha . As long as it’s a symlink, when you node_modules/.bin/mocha (for which mocha in a scripts entry is shorthand) it actually runs node_modules/mocha/bin/mocha . Most likely, however, you copied the project that’s not working, or at least its node_modules folder, in a way that converted the symlink into a copy of the node_modules/mocha/bin/mocha file, resulting in it running in node_modules/.bin , where it won’t find other Mocha files ( ./options.js happens to be the first one, but the issue would be the same no matter which other Mocha files it uses and no matter the order in which it uses them). The most reliable way to fix the faulty project is to delete node_modules and npm i again.

@ScottFreeCode I should have been more careful while describing what I did. I did not literally copy the folder from the working project to the new project. I looked at the package.json of the working project and installed all the modules from there into the new project. I also uninstalled and re-installed mocha couple of times while I was following the suggestions on this thread.

After I wrote the above comment, I thought maybe I should go back and check the symlinks. Symlinks where not there (may be an npm bug??). I manually created the symlinks and it all works fine.

👍 Glad you got it figure out!

Only other things I’d add are:

  • NPM does have a —no-bin-links option that is supposed to install without creating the links — although that shouldn’t be relevant here (I think it’s safe to presume you weren’t using it. )
  • NPM doesn’t always cleanup/fix things on attempts to remove and/or reinstall once this issue has occurred; deleting the folder and then installing is more reliable.

In any case it sounds like you’re good to go for now!

Источник

Answer by Lydia James

I saw a similar issue, and I fixed it by adding —require ts-node/register. So code below might work for you, though I haven’t tested it on react,

The strange domain names that developers bought

,Please be sure to answer the question. Provide details and share your research!

I saw a similar issue, and I fixed it by adding --require ts-node/register. So code below might work for you, though I haven’t tested it on react

npx mocha --require ts-node/register --require esm src/**/*.spec.ts

Or in package.json scripts (both options work, choose whichever you like):

"scripts": {
    "test": "mocha -r esm -r ts-node/register src/**/*.spec.ts",
    "test-ts": "ts-mocha -r esm -p tsconfig.json src/**/*.spec.ts"
}

And don’t forget to add esm to devDependencies:

npm install --save-dev esm

so in package.json it is gonna be

"devDependencies": {
    "esm": "^3.2.25"
}

Answer by Isaac Black


Answer by Guadalupe Griffin

Using webpack-dev-middleware,Using webpack-dev-server,Now let’s configure webpack to handle TypeScript:

First install the TypeScript compiler and loader by running:

npm install --save-dev typescript ts-loader

project

  webpack-demo
  |- package.json
+ |- tsconfig.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
    |- index.js
+   |- index.ts
  |- /node_modules

Let’s set up a configuration to support JSX and compile TypeScript down to ES5…

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node"
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

./index.ts

- import _ from 'lodash';
+ import * as _ from 'lodash';

  function component() {
    const element = document.createElement('div');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
  }

  document.body.appendChild(component());

tsconfig.json

  {
    "compilerOptions": {
      "outDir": "./dist/",
+     "sourceMap": true,
      "noImplicitAny": true,
      "module": "commonjs",
      "target": "es5",
      "jsx": "react",
      "allowJs": true,
      "moduleResolution": "node",
    }
  }

webpack.config.js

  const path = require('path');

  module.exports = {
    entry: './src/index.ts',
+   devtool: 'inline-source-map',
    module: {
      rules: [
        {
          test: /.tsx?$/,
          use: 'ts-loader',
          exclude: /node_modules/,
        },
      ],
    },
    resolve: {
      extensions: [ '.tsx', '.ts', '.js' ],
    },
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },
  };

For example if we want to install lodash we can run the following command to get the typings for it:

npm install --save-dev @types/lodash

custom.d.ts

declare module '*.svg' {
  const content: any;
  export default content;
}

Answer by Ariya Shannon

The configuration from the base file are loaded first, then overridden by those in the inheriting config file. All relative paths found in the configuration file will be resolved relative to the configuration file they originated in.,It’s worth noting that files, include and exclude from the inheriting config file overwrite those from the
base config file, and that circularity between configuration files is not allowed.,Default: The longest common path of all non-declaration input files. If composite is set, the default is instead the directory containing the tsconfig.json file.

Specifies an allowlist of files to include in the program. An error occurs if any of the files can’t be found.

{  "compilerOptions": {},  "files": [    "core.ts",    "sys.ts",    "types.ts",    "scanner.ts",    "parser.ts",    "utilities.ts",    "binder.ts",    "checker.ts",    "tsc.ts"  ]}

Answer by Kyler Delacruz


Answer by Myla Juarez

After Jumping from React to Angular, The First thing i fall in love was TypeScript. I loved it so much that i have planned it to use in React instead of normal JavaScript.,I am posting this tiny piece of information because I am sure there will be others who are slowly moving from JavaScript to TypeScript and if they encounter this Error, they can solve it within a minute. Although in my case it took me 5 minutes to figure out what’s going wrong.,Developer? Trying to be One! Work: https://play.google.com/store/apps/developer?id=Amandeep+Kochhar


Answer by Mikaela Chavez

Caveat: the compiler option —noEmitOnError makes TypeScript refuse to emit JavaScript when it finds compile errors. Run tsc —noEmitOnError false to get around it.,TypeScript will turn your code into JavaScript even when there are compile errors.,Make a file somewhere among your TypeScript source. Call it types.d.ts (or whatever; see above) and put in it:

When I import a JS module that is not built for TS, the compiler gets in my way. It says stuff like:

index.ts:2:24 - error TS7016: Could not find a declaration file for module 'deppy'. '/home/jessitron/code/atomist-blogs/deppy/index.js' implicitly has an 'any' type.
  Try `npm install @types/deppy` if it exists or add a new declaration (.d.ts) file containing `declare module 'deppy';`

2 import * as deppy from "deppy"
                         ~~~~~~~

Make a file anywhere among your .ts files. Put in it:

declare module "*";

Watch out: if you create a .d.ts file, then you must teach .gitignore to care about it. You probably have compiler output (including .d.ts) excluded from git. Add a line to the end of .gitignore with a «!» for «don’t ignore this,» followed by your filename:

!types.d.ts

Make a file somewhere among your TypeScript source. Call it types.d.ts (or whatever; see above) and put in it:

declare module "your-package-of-interest";

Start with a .d.ts file anywhere in your source directories. (See Fix #3). You can put all of these in types.d.ts or each in its own file, like types/your-package-of-interest.d.ts. Declare the module like this:

declare module "your-package-of-interest" {
    type Stuff = string;
    function happyFunction(parameters: stuff[]): Stuff;
    function happyFunction(orThis: number): Stuff; // overloaded function decl
    // etc etc, all the exports you choose to include. 
}

If the module exports just one thing (like a function or a class), then add a line at the bottom to specify the one exported thing:

declare module "happy-function" {
    function happyFunction(parameters: stuff[]): string;
    export = happyFunction;
}

Testing for React Native components is broken

This week, I generated a react-native app with react-native v2.0.1. It went something like this:

The resulting Jest-based testing setup does not function.

TL;DR

You can get a nice Mocha testing setup working for React Native using a custom Mocha config and react-native-mock-render. See below for the modules you’ll need to add and the configuration.

The problem

Using react-native-cli v2.0.1, I ran react-native init testproj to generate a clean React Native project. It spit out a project directory with React Native v0.57.3, Jest v23.6.0, and metro-react-native-babel-preset v0.48.1. I then added a simple test called App.test.js like so:

describe('a test test', () => {
  it('is true', () => {
    expect(true).toBe(true);
  });
});

However, running yarn test results in:

$ jest
 FAIL  ./App.test.js
  ● Test suite failed to run

    Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "/Users/bgladwell/repos/testproj"

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.259s, estimated 1s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

There is some problem with how Jest and Babel are (not) working together. In this case, Jest’s out-of-the-box configuration is working against us. Dependencies for Jest and Metro are apparently causing some conflict between Babel 6 and Babel 7, but it’s quite difficult to isolate which packages are causing the conflict.

There are open issues for React Native and Metro, but no definitive solutions.

A proposal in both issue threads is to change the babel preset used in .babelrc from metro-react-native-babel-preset to react-native. It doesn’t surprise me that this works for some people in some situations, but I don’t think it’s a good idea. Here’s why:

The react-native preset is short for babel-preset-react-native. As you might guess, this is a Babel preset package for working with react native code. What is less obvious is that babel-preset-react-native depends on Babel 6 and has been superseded by metro-react-native-babel-preset, which depends on Babel 7. So to regress back to babel-preset-react-native means forcing our project to continue to depend on Babel 6, something that the react-native maintainers have decided against. Also, we have to worry about more than Jest here; Metro (the React Native bundler) depends on Babel 7. It seems unwise to have our tests compiled with Babel 6 while our development and production code is compiled by Babel 7.

Not really sure how to fix Jest

There may be some way to resolve this issue using Jest. I’m just not sure how. And neither does anyone else, judging by the React Native and Metro issues.

But, I am able to get tests working using Mocha. Here’s how:

Mocha

Let’s add Mocha and Enzyme to our project so that we can test React components. We also add Chai for assertions. Of course, we’ll have to add the Enzyme React 16 adapter. We will configure Enzyme to use the adapter below.

yarn add -D mocha chai enzyme enzyme enzyme-adapter-react-16

Next, update App.test.js so that it does something sorta like a real component test:

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Text } from 'react-native';
import { expect } from 'chai';

import App from './App';

Enzyme.configure({ adapter: new Adapter() });

describe('<App>', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<App />);
  });
  it('renders default Text', () => {
    expect(wrapper.find(Text)).to.have.lengthOf(3);
  });
});

Our test assumes that App.js renders a simple component with three <Text> component children, which is how react-native init generated it.

Ok, let’s try to run our test:

node_modules/.bin/mocha App.test.js

No dice. We get this error:

...
App.test.js:1     
(function (exports, require, module, __filename, __dirname) { import { shallow } from 'enzyme';      
                                                              ^^^^^^                                 

SyntaxError: Unexpected token import
...

That makes sense. We need Babel to compile those import statements, but Babel is not yet involved. Let’s change that:

If you check Babel’s documentation for how to use Babel with Mocha, it says to do this:

mocha --require babel-register

The --require option loads a npm module at runtime — in this case it is telling Mocha to compile everything with Babel. But this is incorrect in our case! These instruction are out of date. babel-register is the Babel 6 version of what we want to do. We actually need to do:

mocha --require @babel/register

@babel/register is the Babel 7 version. Let’s try it:

node_modules/.bin/mocha --require @babel/register  App.test.js

Oh no what’s this? Another error:

module.js:491                                     
    throw err;                                    
    ^                                             

Error: Cannot find module 'Platform'
...

Mocking native modules

This error is telling us that that Node is not able to load Platform. This is because Platform is a native module provided by React Native — i.e. a non-JavaScript module written in Objective-C or Java. Happily, this problem is also solvable by mocking the native modules. If you Google around, most solutions will direct you to a package called react-native-mock. I’m sure this package worked at some point, but it is no longer maintained, and it does not work with React 16.

However, the good people at Root Insurance have forked the project and improved it. Lets use their module: react-native-mock-render.

yarn add -D react-native-mock-render

Now what happens if we also load react-native-mock-render with our tests?

node_modules/.bin/mocha --require @babel/register --require react-native-mock-render/mock App.test.js

OMG! IT WORKED!

Compiling node_modules

If the above is working for you, you’re good to go. However, it wasn’t enough for my project.

Let’s add a fairly large dependency to our project: Native Base. This will bring in a host of other modules.

yarn add native-base

Now add a Native Base component to the App.js file that was generated by react-native init. It should look something like this:

import React, {Component} from 'react';           
import {Platform, StyleSheet, Text, View} from 'react-native';                                       
import { Spinner } from 'native-base';            

const instructions = Platform.select({            
  ios: 'Press Cmd+R to reload,n' + 'Cmd+D or shake for dev menu',                                   
  android:                                        
    'Double tap R on your keyboard to reload,n' +                                                   
    'Shake or press menu button for dev menu',    
});                                               

type Props = {};                                  
export default class App extends Component<Props> {                                                  
  render() {                                      
    return (                                      
      <View style={styles.container}>             
        <Spinner />                               
        <Text style={styles.welcome}>Welcome to React Native!</Text>                                 
        <Text style={styles.instructions}>To get started, edit App.js</Text>                         
        <Text style={styles.instructions}>{instructions}</Text>                                      
      </View>                                     
    );                                            
  }                                               
}                                                 

const styles = StyleSheet.create({                
  container: {                                    
    flex: 1,                                      
    justifyContent: 'center',                     
    alignItems: 'center',                         
    backgroundColor: '#F5FCFF',                   
  },                                              
  welcome: {                                      
    fontSize: 20,                                 
    textAlign: 'center',                          
    margin: 10,                                   
  },                                              
  instructions: {                                 
    textAlign: 'center',                          
    color: '#333333',                             
    marginBottom: 5,                              
  },                                              
});

All we added was
import { Spinner } from 'native-base';

and
<Spinner />

Now what happens when we run our test?

node_modules/.bin/mocha --require @babel/register --require react-native-mock-render/mock App.test.js

New errors!

...
node_modules/native-base-shoutem-theme/index.js:1                    
(function (exports, require, module, __filename, __dirname) { import connectStyle from "./src/connectStyle";                                                                                               
                                                              ^^^^^^                                 
                                                                                                     
SyntaxError: Unexpected token import
...

Wait, what? This looks like Babel 7 is no longer doing its job. Why is «import» an unexpected token?

The answer is that Babel 7 no longer compiles node_modules by default. This isn’t necessarily bad. If you don’t need to do it, compiling everything in node_modules can add a LOT of overhead to your tests.

But we apparently DO need Babel 7 to compile the modules under node_modules that ship with ES2015 assets. To make that happen, we’re going to create a new Mocha configuration that we load at runtime. As a bonus, we can put some of our general test config stuff (like Enzyme’s adapter config) in there too.

Create config/mocha.js

const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

require('react-native-mock-render/mock');

require('@babel/register')({
  presets: [require('metro-react-native-babel-preset')],
  ignore: [
    function (filepath) {
      const packages = [
        'native-base-shoutem-theme',
      ];
      if (packages.some(p => filepath.startsWith(`${__dirname}/node_modules/${p}`))) {
        return false;
      }
      return filepath.startsWith(`${__dirname}/node_modules`);
    },
  ],
});

As you can see, at the top of the file we configure Enzyme with the React 16 adapter, so we can remove that stuff from our test file. We also pull in react-native-mock-render, so we can now omit that from the command line when running our tests.

Then, we require @babel/register (the same module that we were --requireing on the command line` and pass it a configuration object.

presets: [require('metro-react-native-babel-preset')]

This specifies the same Babel preset that is listed in the .babelrc file generated by native-react init. As you may recall, it is the new version of babel-preset-react-native that uses Babel 7.

Next comes the ignore array. You can find documentation for how this works here. In our case, we are providing a function that returns false for anything we do want Babel to compile, true for anything it should skip.

The function says to compile anything in the packages array, skip anything else under node_modules, compile everything else. In our case we want to compile native-base-shoutem-theme, the module with the error from above.

We could simply write the ignore array as an empty array, but this would mean Babel should compile everything, including node_modules. That seems unnecessarily slow. Using the ignore function above, we can simply add the name of any module that ships code with ES2015 import semantics.

Run the new config like this:

node_modules/.bin/mocha --require config/mocha.js App.test.js

And there you go! Working React Native component tests with Mocha and Babel 7.

Summary

We changed the files and commands we used throughout this post. Here are the final versions:

The example test:

import React from 'react';
import { shallow } from 'enzyme';
import { Text } from 'react-native';
import { expect } from 'chai';

import App from './App';

describe('<App>', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<App />);
  });

  it('renders default Text', () => {
    expect(wrapper.find(Text)).to.have.lengthOf(3);
  });
});

The Mocha configuration file:

const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

require('react-native-mock-render/mock');
require('@babel/register')({
  presets: [require('metro-react-native-babel-preset')],
  ignore: [
    function (filepath) {
      const packages = [
        'native-base-shoutem-theme',
      ];
      if (packages.some(p => filepath.startsWith(`${__dirname}/node_modules/${p}`))) {
        return false;
      }
      return filepath.startsWith(`${__dirname}/node_modules`);
    },
  ],
});

We added the following modules to make all this work:

yarn add -D mocha chai enzyme enzyme enzyme-adapter-react-16 react-native-mock-render

To run a test:

node_modules/.bin/mocha --require config/mocha.js App.test.js

You can/should of course put that in a npm script and omit the node_modules/.bin/ as well as change App.test.js to be something like **/*.test.js.

P.S.

Snapshot testing with Mocha seems to work with with snap-shot-it and enzyme-to-json. So far, I’m quite happy with Mocha as my React Native test framework.

When I am running npm run test (mocha), I am getting this message.
Using following: npm install —save mocha ganache-cli web3@1.0.0-beta.26
Please advice.

> smart@1.0.0 test C:Smart
> mocha

Error: Cannot find module 'web3'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:Smarttestinbox.test.js:3:14)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at C:Smartnode_modulesmochalibmocha.js:253:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (C:Smartnode_modulesmochalibmocha.js:250:14)
    at Mocha.run (C:Smartnode_modulesmochalibmocha.js:577:10)
    at Object.<anonymous> (C:Smartnode_modulesmochabin_mocha:591:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! smart@1.0.0 test: `mocha`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the smart@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

Ismael's user avatar

Ismael

30k19 gold badges48 silver badges91 bronze badges

asked Apr 24, 2018 at 18:51

monkrus's user avatar

4

If you are on windows, open up your terminal as administrator and run the following command:

npm install —global —production windows-build-tools

answered Oct 11, 2018 at 13:18

Talha Shan's user avatar

Click here follow the steps to fix Mocha Error Cannot Find Module ‘chai’ and related errors.

Instructions

 

To Fix (Mocha Error Cannot Find Module ‘chai’) error you need to
follow the steps below:

Step 1:

 
Download
(Mocha Error Cannot Find Module ‘chai’) Repair Tool
   

Step 2:

 
Click the «Scan» button
   

Step 3:

 
Click ‘Fix All‘ and you’re done!
 

Compatibility:
Windows 7, 8, Vista, XP

Download Size: 6MB
Requirements: 300 MHz Processor, 256 MB Ram, 22 MB HDD

Limitations:
This download is a free evaluation version. To unlock all features and tools, a purchase is required.

Mocha Error Cannot Find Module ‘chai’ Error Codes are caused in one way or another by misconfigured system files
in your windows operating system.

If you have Mocha Error Cannot Find Module ‘chai’ errors then we strongly recommend that you

Download (Mocha Error Cannot Find Module ‘chai’) Repair Tool.

This article contains information that shows you how to fix
Mocha Error Cannot Find Module ‘chai’
both
(manually) and (automatically) , In addition, this article will help you troubleshoot some common error messages related to Mocha Error Cannot Find Module ‘chai’ error code that you may receive.

Note:
This article was updated on 2023-02-03 and previously published under WIKI_Q210794

Contents

  •   1. What is Mocha Error Cannot Find Module ‘chai’ error?
  •   2. What causes Mocha Error Cannot Find Module ‘chai’ error?
  •   3. How to easily fix Mocha Error Cannot Find Module ‘chai’ errors

What is Mocha Error Cannot Find Module ‘chai’ error?

The Mocha Error Cannot Find Module ‘chai’ error is the Hexadecimal format of the error caused. This is common error code format used by windows and other windows compatible software and driver vendors.

This code is used by the vendor to identify the error caused. This Mocha Error Cannot Find Module ‘chai’ error code has a numeric error number and a technical description. In some cases the error may have more parameters in Mocha Error Cannot Find Module ‘chai’ format .This additional hexadecimal code are the address of the memory locations where the instruction(s) was loaded at the time of the error.

What causes Mocha Error Cannot Find Module ‘chai’ error?

The Mocha Error Cannot Find Module ‘chai’ error may be caused by windows system files damage. The corrupted system files entries can be a real threat to the well being of your computer.

There can be many events which may have resulted in the system files errors. An incomplete installation, an incomplete uninstall, improper deletion of applications or hardware. It can also be caused if your computer is recovered from a virus or adware/spyware
attack or by an improper shutdown of the computer. All the above actives
may result in the deletion or corruption of the entries in the windows
system files. This corrupted system file will lead to the missing and wrongly
linked information and files needed for the proper working of the
application.

How to easily fix Mocha Error Cannot Find Module ‘chai’ error?

There are two (2) ways to fix Mocha Error Cannot Find Module ‘chai’ Error:

Advanced Computer User Solution (manual update):

1) Start your computer and log on as an administrator.

2) Click the Start button then select All Programs, Accessories, System Tools, and then click System Restore.

3) In the new window, select «Restore my computer to an earlier time» option and then click Next.

4) Select the most recent system restore point from the «On this list, click a restore point» list, and then click Next.

5) Click Next on the confirmation window.

6) Restarts the computer when the restoration is finished.

Novice Computer User Solution (completely automated):

1) Download (Mocha Error Cannot Find Module ‘chai’) repair utility.

2) Install program and click Scan button.

3) Click the Fix Errors button when scan is completed.

4) Restart your computer.

How does it work?

This tool will scan and diagnose, then repairs, your PC with patent
pending technology that fix your windows operating system registry
structure.
basic features: (repairs system freezing and rebooting issues , start-up customization , browser helper object management , program removal management , live updates , windows structure repair.)

I’ve had this question on stackoverflow for almost a week, and have yet to get an answer. Basically i have es6 modules that’s compiled through babel & browserify to make me a single bundle file for a cordova app. Now though, I want to test a single module from a test file. So i’ll import the file into the test, and give it a run. However, the babel process does not seem to compile the es6 files included in the tests. I see errors like «import reserved keyword» when mocha runs the specs.

Here’s my grunt file:

module.exports = function (grunt) {

  // Import dependencies
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-babel');

  grunt.initConfig({
    babel: {
      options: {
        sourceMap: true,
        modules: "common"
      },
      test: {
        files: [{
          expand: true,
          cwd: 'test',
          src: ['**/*.js'],
          dest: 'test/compiled_specs',
          ext:'.js'
        }]
      }
    },
    browserify: {
      dist: {
        files: {
          'www/js/bundle.js': ['src/app.js'],
        },
        options: {
          transform: [['babelify', { optional: ['runtime'] }]],
          browserifyOptions: {
            debug: true
          }
        }
      }
    },
    clean: ["test/compiled_specs"],
    jshint : {
      options : {
        jshintrc : ".jshintrc",
      },

      dist: {
        files: {
          src: ["src/**/*.js"]
        }
      }
    },
    sass: {
      dist: {
        options: {
          style: 'compressed'
        },
        files: {
          'www/css/styles.css': 'www/css/sass/styles.scss'
        }
      }
    },
    watch: {
      css: {
        files: ['www/css/sass/*.scss'],
        tasks: ['sass']
      },
      scripts: {
        files: ['src/**/*.js'],
        tasks: ['jshint', 'browserify:dist'],
        options: {
          atBegin: true,
          spawn: true
        },
      },
    },

    mochaTest: {
      test: {
        src: ['test/compiled_specs/**/*_spec.js']
      }
    }
  });

  grunt.registerTask("default", ['sass','watch']);
  grunt.registerTask("test", ['clean', 'babel', 'mochaTest']);

};

Понравилась статья? Поделить с друзьями:
  • Mobile friendly другая ошибка
  • Mobile crane error
  • Mitsubishi ошибка b1b06
  • Mitsubishi pajero sport ошибка p1766
  • Mitsubishi pajero sport ошибка p0421