Code Monkey home page Code Monkey logo

mochapack's Introduction

mochapack Join the chat at https://gitter.im/sysgears/mochapack npm package Build Status Linux Build Status Windows codecov Twitter Follow

This project is a fork of mocha-webpack. We have created this fork since there is no visible activity from original author for a long time.

mocha test runner with integrated webpack precompiler

mochapack is basically a wrapper around the following command...

$ webpack test.js output.js && mocha output.js

... but in a much more powerful & optimized way.

CLI

mochapack ...

  • precompiles your test files automatically with webpack before executing tests
  • handles source-maps automatically for you
  • does not write any files to disk
  • understands globs & all other stuff as test entries like mocha

Benefits over plain mocha

  • has nearly the same CLI as mocha
  • you don't rely on hacky solutions to mock all benefits from webpack, like path resolution
  • mochapack provides a much better watch mode than mocha

Watch mode (--watch)

Unlike mocha, mochapack analyzes your dependency graph and run only those test files that were affected by this file change.

You'll get continuous feedback whenever you make changes as all tests that are related in any way to this change will be tested again. Isn't that awesome?

If any build errors happens, they will be shown like below

CLI

Which version works with mochapack?

mochapack works with

  • webpack in versions 4.x.x - 5.x.x
  • mocha in versions 5.x.x - 9.x.x

Installation

Install mochapack via npm install

$ npm install webpack mocha mochapack --save-dev

and use it via npm scripts in your package.json

Further installation and configuration instructions can be found in the installation chapter.

Sample commands

run a single test

mochapack simple.test.js

run all tests by glob

mochapack "test/**/*.js"

Note: You may noticed the quotes around the glob pattern. That's unfortunately necessary as most terminals will resolve globs automatically.

run all tests in directory "test" matching the file pattern *.test.js (add --recursive to include subdirectories)

mochapack --glob "*.test.js" test

Watch mode? just add --watch

mochapack --watch test

License

This source code is licensed under the MIT license.
Copyright © 2016-2017 Jan-André Zinser
Copyright © 2018 SysGears (Cyprus) Limited.

mochapack's People

Contributors

andykais avatar astorije avatar darrinholst avatar dependabot[bot] avatar ezze avatar flui avatar greenkeeper[bot] avatar jamesmcmahon avatar jayaddison avatar jleft avatar karlwilbur avatar larixer avatar modosc avatar nickradford avatar nvitius avatar pkuczynski avatar randycoulman avatar rivayama avatar sebamarynissen avatar slinkkay avatar sodatea avatar t-kuni avatar techmunk avatar terrenceljones avatar thiagoa avatar vikhyat avatar willsoto avatar yachaka avatar zinserjan avatar zjxiaohan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mochapack's Issues

loaders not being respected

Hi, I'm a brand new user, so I'm probably doing something wrong, but when trying to use purs-loader, I get errors about misunderstood syntax because my purescript hasn't gone through the loader.

Invocation: ./node_modules/mochapack/bin/mochapack --webpack-config webpack.config.test.js --webpack-env test

However, running webpack --config webpack.config.test.js --env test completes fine, so it looks like my loaders are set up correctly.

Happy to help debug etc.

Multiple reporters support

Is it possible to add the multiple reporters support in mochapack? Since mocha has supported it (mochajs/mocha#1360).

Currently got the error "Error: Duplicating arguments for "--reporter" is not allowed. "--reporter spec --reporter xunit" was provided, but expected "--reporter spec"".

[Bug] Support for mocha v9

Describe the bug

When I try to install mochapack, npm throws error

Screenshots

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/mocha
npm ERR!   dev mocha@"^9.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer mocha@">=6 <9" from [email protected]
npm ERR! node_modules/mochapack
npm ERR!   dev mochapack@"^2.1.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/vinayak/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/vinayak/.npm/_logs/2021-06-08T05_19_22_481Z-debug.log

Environment if relevant (please complete the following information):

  • OS: macOS Big Sur
  • Node version 16.3.0
  • Mochapack version 2.1.2
  • Webpack version 4

Additional context

Mocha released v9 few hours ago.

Warning: the engine "pm" appears to be invalid

  • I'd be willing to submit the fix

Describe the bug

yarn install on a project using [email protected] produces a warning warning [email protected]: The engine "pm" appears to be invalid.

To Reproduce

yarn init
yarn add -D mochapack
yarn install

Environment if relevant (please complete the following information):

  • OS: OSX (macOS Catalina)
  • Node version v13.12.0
  • Mochapack version 2.0.0
  • Webpack version 4.43.0

[Feature] Allow usage of custom Mocha initializer

  • I'd be willing to implement this feature

User Story

It's a pretty big barrier to entry for testing to get a good environment set up for Electron projects. It would be great to be able to run electron-mocha instead of mocha for Electron apps that are built using Webpack (specifically electron-webpack).

Proposed Solution

Add a flag such as --electron to run electron-mocha wherever vanilla mocha would otherwise be used. This has been discussed over here: jprichardson/electron-mocha#102

Drawbacks

  • It's another dependency to keep up with (though it could probably be labeled as a peer dependency since not all users would need it)
  • electron-mocha includes a few flags that are not standard. These would need to be handed off to it somehow. Flags not used by regular mocha should quickly throw an error if a user tries to include them without --electron (this would probably provide some extra motivation for #34 to be tackled)
  • If devs are not building with electron-webpack their project structure might deviate from what's expected. This means there would have to be a way to inform electron-mocha of what files to consider renderer vs. main

Alternatives

Currently have a POC project electron-playground which involves maintaining separate scripts for testing:

  • Code that has to be run through Webpack before testing (such as .vue files)
  • Code that relies on electron and runs in the main process
  • Code that relies on electron and runs in the renderer process.
  • e2e tests

The tests that require electron are named .e.spec.ts and those that require webpacking are named w.spec.ts to ensure the test runner does not try and run something it can't handle per specific script.

This is cumbersome. electron-mocha does involve spinning up a process for main and renderer tests separately, but this could probably be handled gracefully by mochapack. That would condense all 3 unit test scripts here into one. Basically instead of running one instance of mocha, it would spin up two concurrently but relying on the same bundled code.

e2e tests can and should be handled separately, so handling those in a separate script is not an issue.

[Bug]

  • I'd be willing to submit the fix
    maybe.
    Describe the bug

A clear and concise description of what the bug is.
I attempt to run the test suit and I receive this error:
Error: ENOENT: no such file or directory, chdir '.tmp/mochapack/1565219434941'
To Reproduce
I just attempt to run this from the terminal
"test": "mochapack --bail --timeout 8000 --exit --recursive --webpack-config webpack.config.test.js",

The minimal information needed to reproduce your issue (ideally a very minimal project setup published on GitHub).
Note that bugs without minimal reproductions might be closed.

Screenshots

If applicable, add screenshots to help explain your problem.

Environment if relevant (please complete the following information):

  • OS: [e.g. OSX, Linux, Windows, ...]
    OSX
  • Node version [e.g. 8.15.0, 10.15.1, ...]
    10.5
  • Mochapack version [e.g. 1.1.3, ...]
    5.2
  • Webpack version [e.g. 4.26.1, ...]
    4.38
    Additional context

Add any other context about the problem here.

my webpack config:

'use strict';

const nodeExternals = require('webpack-node-externals');
const DotenvFlow = require('dotenv-flow-webpack');

module.exports = {
  entry: './polarity.js',
  mode: 'development',
  target: 'node',
  devtool: 'inline-cheap-module-source-map',
  node: {
    __dirname: false
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      { test: /\.ts$/, use: ['ts-loader'] },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre' }
    ]
  },
  externals: [nodeExternals()],
  plugins: [new DotenvFlow()]
};

[Bug] --recursive is not working properly

  • I'd be willing to submit the fix

Describe the bug
When test are in multiple subdirectories, adding --recursive will not help to reach them, neithe rusing --glob or directly the glob string.

To Reproduce
Create a folder stricture like:

components/
 |-- component-a/
 |     |-- component-a.spec.js
 | -- coponent-b/
        |-- sub-components
        |      |-- subcomponent-1
        |      |     |-- subcomponent-1.spec.js
        |      |-- subcomponent-2 
        |      |     |-- subcomponent-2.spec.js
        |      |-- component-b.spec.js

If you run mochapack components/**/*.spec.js it returns 2 test passing (component A and B, but no subcomponent test).
If you run mochapack components/**/*.spec.js --recursive it returns 2 test passing too.
If your run mochapack --glob '*.spec.js' components it returns 0 test passing.
If your run mochapack --glob '*.spec.js' components/** it returns 2 test passing.
If your run mochapack --glob '*.spec.js' components --recursive it returns 0 test passing.
If your run mochapack --glob '*.spec.js' components/** --recursive it returns 0 test passing !!.

The subcomponent test are never reached, and using --recursive with --glob causes no test found when without recursive it is finding test.

I am testing putting command in package.json and running via yarn.

Environment if relevant (please complete the following information):

  • OS: OSX 10,15,2
  • Node version 13.4.0
  • Mochapack version 1.1.13
  • Webpack version 4.39.1

[Feature/help] running with child processes

Hi, thank you for maintaining this fork! I have a project that creates child processes from other webpack entrypoints. Minimally reproducible example:

// webpack.config.js
const path = require('path')

module.exports = {
  target: 'node',
  node: {
    dirname: true
  },
  mode: 'development',
  entry: {
    main: './src/main.js',
    child: './src/child.js'
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].js'
  }
}
// test_sample.js
import {startFork} from './main';

describe('me', () => {
  it('test only', () => {
    console.log('forky')
    startFork();
  });
});
// src/main.js
import {fork} from 'child_process';

export const startFork = () => {
  console.log('starting fork');
  fork('./child.js');
};
// src/child.js
import * as path from 'path'

console.log('im a fork')

Running the tests with mochapack (or mocha-webpack) will fail because a fork (or any code that expects a physical file to work with from an entrypoint) cannot use the entrypoint.

npx mochapack test_sample.js
Error: Cannot find module '/Users/andrew/Code/development/sample-failure/build/child.js'

What is the course of action here? Is there a simple workaround? If not, this is a feature request that proposes actually writing code to the build folder, which is not something mochapack/mocha-webpack has done in the past

[Bug] v2.0.1 breaks testing in Nuxt project

  • I'd be willing to submit the fix

Describe the bug

v2.0.1 breaks testing for Nuxt project (with Vuetify). This may be happening with other frameworks/setups, but I discovered this bug with a Nuxt project. Essentially, the tests no longer run. mochapack is able to succesfully compile the project, but it doesn't run any of the tests. It just completes with "0 passing".

I think I have narrowed this down to the change addressed in this commit. chunk.isOnlyInitial() properly chunks the modules, but chunk.hasEntryModule() appears to only pass for a single chunk.

To Reproduce

See this repo

Environment if relevant (please complete the following information):

  • OS: Linux
  • Node version: 12.16.3
  • Mochapack version: 2.0.1
  • Webpack version: 4.43.0

[Bug] Webpack 5 warns about absolute paths on Windows

  • I'd be willing to submit the fix

I am using mochapack in a project of mine and recently upgraded to webpack 5. The migration was succesful thanks to the newly released version. Thanks for the great work!

There's one minor issue though that I encountered during the migration. Webpack 5 gives the following warning when running the tests:

Warning in ./node_modules/mochapack/lib/entry.js

  Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths.
  Invalid dependencies may lead to broken watching and caching.
  As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior.
  Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories).
  Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories).
  Globs: They are not supported. Pass absolute path to the directory as context dependencies.
  The following invalid values have been reported:
   * "C:/Users/my/test/file.js"

The reason is that webpack fails to recognize that C:/Users/my/test/file.js is an absolute path, as it expects it to be C:\Users\my\test\file.js.

I've been able to fix it by modifying entryLoader.ts by doing

import path from 'path';

const entries = config.getFiles().map(file => path.normalize(file));

See also https://github.com/sysgears/mochapack/blob/master/src/webpack/loader/entryLoader.ts#L35.

Alternatively I think it should also be possible to just use path.normalize() instead of the normalize-path module:

export class EntryConfig {
  files: Array<string>

  constructor() {
    this.files = []
  }

  addFile(file: string): void {
    const normalizedFile = path.normalize(file)
    this.files.push(normalizedFile)
  }

  removeFile(file: string): void {
    const normalizedFile = path.normalize(file)
    this.files = this.files.filter(f => f !== normalizedFile)
  }

  getFiles(): Array<string> {
    return this.files
  }
}

To Reproduce

Run mochapack on Windows with Webpack 5.

Environment:

  • OS: Windows 10
  • Node version: 14.15.5
  • Mochapack version: 2.1.0
  • Webpack version: 5.37.0

[Bug] SyntaxError: Unexpected token 'export'

  • I'd be willing to submit the fix

Describe the bug

I have a Nuxt application with a library of @adonisjs/websocket-client, when I compile it with Nuxt it works but when I use to test my application using mochapack it runs into an error of: SyntaxError: Unexpected token 'export' here is the full error:

node_modules/@adonisjs/websocket-client/dist/Ws.es.js:2507
export default index;
^^^^^^

SyntaxError: Unexpected token 'export'

To Reproduce

  1. Create a nuxt app using npx create-nuxt-app <app-name> or yarn create nuxt-app <app-name>
  2. Then install @adonisjs/websocket-client
  3. Import Ws from @adonisjs/websocket-client in pages/index.vue
  4. Configure mochapack to be able to test Nuxt app here is a link to set it up: Setup for Vue and Mochapack
  5. Run test and the error will occur

Here is a more details result of the error:

➜ npm run test

> [email protected] test .../nuxt-mochapack
> mochapack

 WEBPACK  Compiling...

  [=========================] 100% (completed)

 WEBPACK  Compiled successfully in 756ms

 MOCHA  Testing...

 RUNTIME EXCEPTION  Exception occurred while loading your tests

.../nuxt-mochapack/node_modules/@adonisjs/websocket-client/dist/Ws.es.js:2507
export default index;
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:891:16)
    at Module._compile (internal/modules/cjs/loader.js:941:27)
    at Module._extensions..js (internal/modules/cjs/loader.js:1011:10)
    at Object.module_1.default._extensions.<computed> [as .js] (.../nuxt-mochapack/node_modules/mochapack/src/util/registerRequireHook.ts:99:53)
    at Module.load (internal/modules/cjs/loader.js:822:32)
    at Function.Module._load (internal/modules/cjs/loader.js:730:14)
    at Module.require (internal/modules/cjs/loader.js:864:19)
    at require (internal/modules/cjs/helpers.js:74:18)

Environment if relevant (please complete the following information):

  • OS: Ubuntu 20.04
  • Node version: 13.0.1
  • Mochapack version: ^1.1.13
  • Webpack version: (Not sure what version Nuxt is using)

Additional context

Remove some information replaced them with ... for brevity. I also tried the configuring my mochapack.config.js with esModule: false options for file-loader but that did not do the trick. Just some more information Nuxt uses webpack as well and it compiles and run the application without any issues, only when I try to run the test with mochapack.

--include does not work when in 'opts' file [Bug]

  • I'd be willing to submit the fix

Describe the bug
I am upgrading our libraries, so I swapped to mochapack and now I have an issue:
We are having global memory clearing method in cleanUpResources.js

afterEach('Cleanup after test', function () {
    // Remove all listeners added by our test
    console.log('-- clear --');
    listeners.window.forEach((listener) => window.removeEventListener(listener.type, listener.listener));
    listeners.document.forEach((listener) => document.removeEventListener(listener.type, listener.listener));
    listeners.window = [];
    listeners.document = [];
    // Restore sinon sandbox
    sinon.reset();
    sinon.restore();
});

Loading this file using
--include ./test/cleanupResources.js
also using parameter
--opts mochapack.opts

--colors
--recursive
--full-trace
--require mock-local-storage
--require ./test/test_helpers.js
--include ./test/cleanupResources.js

clear and concise description of what the bug is.

when I have the include inline directly it loads the cleanup file. When I have it in the opts file, it does not.

To Reproduce

You can do the same thing I did... have an --include with some file and in it have afterEach with console.log and check the difference with inline and in opts solution.

Environment if relevant (please complete the following information):

Currently I am bypassing this using the inline solution.

Is there a way to measure execution time of testcases

Is there any option in the CLI to pass in order to measure the execution time for testcases

It is always good to know as how long it took to execute the complete testcases. There is a use case where I dont want to let testcases run for more than some set X unit of time.

If there is an CLI option lsomething like --exec-time which can provide the execution time will help

In the console, on execution or failure CLI should gives the total time it took to execute the testcases if --exec-time is set in the script/command

re-clone mocha-webpack repo?

there is a lot of useful blame history that could be used from the mocha-webpack repo - is there a reason you dropped all the git history?

[Question/Feature]

Hello,

First of all, Thanks for the Great job on maintaining this project. It's awesome !

I'm using mochapack in my project and my issue is when I generate a test results report for Sonar - using mocha-sonarqube-reporter - this report is ignored by Sonar because it only reference the generated webpack bundle name and not the effectives tests files.

image

It's possible to add a describe block (with file name) to each test file, but I think is bad.

Do you have any idea to generate a report with the correct test files references ? Do you think that it's possible to implement a new feature fixing this ?

Best regards

[Bug] imports do not work with sass-loader and stdin template

  • I'd be willing to submit the fix

Describe the bug

I got the following webpack config for the sass-loader:

              {
                "loader": "sass-loader",
                "options": {
                  "sourceMap": true,
                  "outputStyle": "expanded",
                  "implementation": {
                    "info": "dart-sass\t1.22.10\t(Sass Compiler)\t[Dart]\ndart2js\t2.4.1\t(Dart Compiler)\t[Dart]",
                    "types": {}
                  },
                  "data": "@import \"~assets/scss/_replacements/vuetify-main.scss\""
                }
              }

Error in ./node_modules/vuetify/src/components/VCalendar/mixins/calendar-with-events.sass

Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Can't find stylesheet to import.

2 │ @import 'vuetify-variables';
│ ^^^^^^^^^^^^^^^^^^^

app/assets/scss/_replacements/vuetify-main.scss 2:9 @import
stdin 1:9 root stylesheet
in about:/app/assets/scss/_replacements/vuetify-main.scss (line 2, column 9)
at /app/node_modules/webpack/lib/NormalModule.js:316:20
at /app/node_modules/loader-runner/lib/LoaderRunner.js:367:11
at /app/node_modules/loader-runner/lib/LoaderRunner.js:233:18
at /app/node_modules/sass-loader/dist/index.js:89:7


I can try all variations of the import, but the sub-import in the imported file cannot be resolved.

**To Reproduce**

add an import in the stdin template for sass-loader (see above)

**Environment if relevant (please complete the following information):**

 - OS: Linux on Docker
 - Node version v12.14.1
 - Mochapack version 2.0.0
 - Webpack version 4.43.0

Thanks for giving me an idea. Is it the ~ in the import patH?

Using watch fail on first refresh

Hi guys, I have a test with some typescript mixins, if I run test, all works!

BaseField.vue Component
✓ Is in wrapper element
✓ Has slot
✓ It contains a valid button-group
✓ It contains a valid button-group label
✓ It not contains a default required *
✓ It contains a default required *
✓ Is visible by default
✓ Can toggle visibility
✓ Is does not show any errors
✓ Is show errors when triggered

But, if I run test with --watch options, first time all works, but at the first watcher refresh I get:

TS2307: Cannot find module '!../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js' or its corresponding type declarations.

For each .ts file that it tries to load!

[Feature] Pass through arguments into Mocha

  • I'd be willing to implement this feature

Describe the user story

Why

As user of mochapack
I want be able to use all the command line features of mocha, both currently and as mocha is updated
So that I don't have to wait on mochapack to be updated

Acceptance Criteria

Scenario: 
Given a command line option that mochapack doesn't currently support (ie, `--forbid-pending` or `--file`)
When I add that option when I run mochapack, `npx mochapack --forbid-pending *.test.js`
Then I see mochapack behavior in the same way as the option would behavior in mocha

Describe the solution you'd like

While working on #30 it became clear to me that while it would be easy to add additional mocha options to the cli, it feels sub-optimal to have to essentially write the same code and tests for each option.

I'd like to refactor and add to the internals of mochapack to support a passthrough of args to mocha. That way we don't need to scramble to support additional args as the mocha people add them.

Describe the drawbacks of your solution

Not sure how this would effect the programmatic API of the mochapack (or if we care about that as a feature). There is a possibility of breaking changes to that API, but as far as I can tell the CLI options are 1 for 1.

I also think it's possible to implement the changes in a way that the API does not break, with possible deprecation markers being added to certain methods that we want to remove in the future.

Describe alternatives you've considered

Looking for feedback on this thread of alternative solutions.

Additional context

This make sense to me given the current requested features from both this project and mocha-webpack. I also think this could result in a simpler code base as right now mochapack is deeply concerned with the particulars of mocha's options. I think we should get out of the business of trying to re-implement mocha features.

I am willing to work on this. It feels like a decent chunk of work, though I am admittedly new the project, so my estimate may be off. I wanted to get buy in before embarking on a PR.

Command line option requests:

Probably missed a few, but you get the gist 😆

[Feature] Webpack v5 compatibility

  • I'd be willing to implement this feature I tried to implement this feature but did not achieve completion; see #83

Describe the user story
webpack v5.0.0 was released on 2020-10-10 and is likely to see gradual uptake as new projects begin using it and existing projects migrate to it. As a user of webpack v4 and mochapack, I'd appreciate the ability to have an upgrade path for my project in order to run tests based on webpack v5.

Describe the solution you'd like
Upgrades to the mochapack CLI to support projects using webpack v5.

Describe the drawbacks of your solution
webpack v5 introduces a number of breaking changes, and it's unclear to me whether it would be possible to support both v4 and v5 from an updated mochapack codebase.

Add support for --file option

--file <file/directory/glob>

Explicitly include a test file to be loaded before other test files files. Multiple uses of --file are allowed, and will be loaded in order given.

Useful if you want to declare, for example, hooks to be run before every test across all other test files.

Files specified this way are not affected by --sort or --recursive.

Files specified in this way should contain one or more suites, tests or hooks. If this is not the case, consider --require instead.

v2.0.0 - Config

Hi,

I am confused as to how to use mochapack v2.0.0. Any doc would be useful on how to pass the config, and what config options are available. Previously, I used mochapack.opts file and provided the same as cli args -

mochapack --opts test/mochapack.opts

The file contents include

--require "@babel/register"
--require "jsdom-global/register"
--require "test/setup.js"
--recursive
"src/**/test/**/*.spec.js" "src/**/*.vue"
--reporter "spec"
--webpack-config test/webpack.config.js

Now, if I run the same way I get exception - WebpackOptionsValidationError: Invalid configuration object.

Tried with

mochapack --webpack-config test/webpack.config.js

Now, webpack config is loaded properly, but how/where do you specify my root .mocharc.json file. Contents are below -

{
  "extension": ["js", "vue"],
  "require": ["@babel/register", "jsdom-global/register", "test/setup.js"],
  "reporter": "spec",
  "spec": ["src/**/test/**/*.spec.js", "src/**/*.vue"],
  "recursive": true
}

The problem with mocharc.json file in root folder - No tests are running.

@Jack-Barry -> Thanks for all your help!

[Bug] image and vue loaders fail in v2.0.0

  • I'd be willing to submit the fix

Describe the bug

I have a project using mochapack with file-loader and vue-loader.
Webpack.config has module.rules for file-loader and vue-loader
{
test: /.vue$/,
use: "vue-loader"
},
{
test: /.(png|svg|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[path][name].[ext]?[hash]",
context: "",
esModule: false
}
}
}
There are others but these are the relevant ones.

I have a script in package.json as follows:
"test": "cross-env NODE_ENV=test mochapack test/**/*-test.js"

When mochapack v1.1.15 is installed the tests run without error.
If v2.0.0 is installed I get errors for img files imported as ... import "../images/exclamation.png";
and errors for vue files

The messages are as follows...

For images:

Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
and for Vue files:

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

| <b-modal
| id="info-dialog"

To Reproduce
I have not had time to whittle the code to a simple example yet, especially since 2.0.0 is only 7 ours old according to github :)

I am registering the issue so you are aware. I will reply when I have a small project to use.

The minimal information needed to reproduce your issue (ideally a very minimal project setup published on GitHub).
Note that bugs without minimal reproductions might be closed.

Screenshots

If applicable, add screenshots to help explain your problem.

Environment if relevant (please complete the following information):

  • OS: Windows 10
  • Node version 12.16.2
  • Mochapack version 2.0.0
  • Webpack version 4.41.5

Yargs dependency leads to vulnerable mem package

The current "yargs": "^11.0.0" dependency has in turn a dependency on
"os-locale": "^2.0.0", which in turn is dependent on
"mem": "^1.1.0" which is vulnerable.

It seems that the only wayout is: bump the version of "yargs" to at least 12.0.0 but 13 is better.

Many thanks for adopting the stale mocha-webpack, by the way.

Support for webpack.config returning array of configs

  • I'd be willing to implement this feature
    I'd certainly be willing to test it with you on my current project.

Describe the user story
This is my first webpack project, but I think I have a good handle on it. It consists of a web app and a library as well. The web app will use the library, but it could be used in other projects. I had decided to split the two before I get too far down the road. I've chosen to write the project in typescript. As any good project has, there is built in unit testing via mocha.
my project builds in both dev and prod modes. To my surprise, It fails testing because the webpack.config returns an array of two webpack.Configuration types.
Now mocha pack is a front end to webpack test.js output.js && mocha output.js as you mention in your documentation. I learned that handling arrays can only be done when you import mocha-webpack-v2.0.0-beta.0; which sounds ominous ; but has been around for a year in alpha as Karma-webpack.rel6.

Now I come to the problem where mochapack does not handle arrays either, the last link in the chain, I believe.

The solution would be for mochapack to check if the webpack.Configuration returned is an array and then merge the content.

Describe the drawbacks of your solution
I have barely looked at your code, but believe merging would not cause any issues, the array of tests just grows based on the merge. you would know better.

This section is important not only to identify future issues, but also to see whether you thought your request through. When filling it, ask yourself "how can I break it".

mochapack would still have to detect that if an array was not given, to continue as normal.

Describe alternatives you've considered
I have tried separate config files, but this really has issues with watching for changes and now supporting two config files.

if push comes to shove, I will try to add it myself, but I'm sure you could do it faster.

thanks for the great tool.

John Talbot
[email protected]

[Bug] Promised webpack config is not resolved

  • I'd be willing to submit the fix

Describe the bug

A Promised Webpack config is not resolved before mochapack uses it.

To Reproduce

Set the --webpack-config to a Webpack config that returns a Promise.

I have a project set up here: electron-playground. Once cloned:

npm i
npm run test:unit

Screenshots

Screen Shot 2019-11-29 at 21 39 50

You'll notice that Webpack begins compiling before it has resolved the config, as evidenced by the timing of the executed console.log.

Environment if relevant (please complete the following information):

  • OS: macOS Catalina 10.15.1
  • Node version v12.8.1
  • Mochapack version 1.1.12
  • Webpack version 4.41.2

Additional context

In my use case, I'm trying to use a Webpack config from electron-webpack that relies on a resolved Promise for the config. I'm not sure where to look exactly to fix this, but I'd imagine it basically involves just awaiting the config from whatever --webpack-config is pointed at before proceeding to run webpack. Happy to help if I can!

Upgrade dependencies

We get following warnings in our project:

warning mochapack > babel-runtime > [email protected]: core-js@<3.0 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
warning mochapack > chokidar > [email protected]: One of your dependencies needs to upgrade to fsevents v2: 1) Proper nodejs v10+ support 2) No more fetching binaries from AWS, smaller package size

[Bug] Webpack env vars are passed incorrectly

  • I'd be willing to submit the fix

Describe the bug

When running node bin/_mocha --webpack-config test/integration/cli/fixture/config/config.env.js --webpack-env.test 0.96726147776912 "test/integration/cli/fixture/simple/simple.js", the environment variable test/integration/cli/fixture/config/config.env.js receives is { test: [ '0.96726147776912', '0.96726147776912' ] } instead of { test: '0.96726147776912' }.

To Reproduce

To reproduce, run the passes --webpack-env object to config test in /test/integration/cli/config.test.js and print the env.

Screenshots

There are no real screenshots. I tried to print parsedArgs in the parse function in /src/cli/parseArgv, and the content doesn't seem correct.

Screenshot from 2019-11-25 14-27-10

Environment if relevant (please complete the following information):

  • OS: Linux
  • Node version 10.16.3
  • Mochapack version 1.1.10
  • Webpack version 4.41.0

Additional context

Not sure if this is related:

if (validOptions.webpackEnv && Array.isArray(validOptions.webpackEnv.env)) {
const [first] = validOptions.webpackEnv.env;
validOptions.webpackEnv.env = first;
}

[Bug] globby error during running on >=1.1.3

  • I'd be willing to submit the fix

Describe the bug

A version < 1.1.3 seems to run okay still, but after the mochapack dependency updates something seems to have broken. I get the following error when I attempt to run mochapack on >=1.1.3:

D:\Projects\JavaScript\JS\MasterClass>npm run test

> [email protected] test D:\Projects\JavaScript\JS\MasterClass
> mochapack --webpack-config webpack.config.test.js --require ./test/test_helper.js ./test/index.spec.js

D:\Projects\JavaScript\JS\MasterClass\node_modules\globby\index.js:50
                ...taskOptions
                ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (D:\Projects\JavaScript\JS\MasterClass\node_modules\mochapack\lib\util\glob.js:16:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1

To Reproduce

run mochapack --webpack-config webpack.config.test.js --require ./test/test_helper.js ./test/index.spec.js. The files that are required for reproduction contain:

webpack.config.js

const path 	= require("path"),
      webpack 	= require("webpack"),
      merge     = require("webpack-merge"),
      APP_DIR   = path.resolve(__dirname, "src"),
      BUILD_DIR = path.resolve(__dirname, "build");


let commonConfig = {
  target: "node",
  output: {
    path: 	BUILD_DIR,
    publicPath: "/",
    filename: 	"bundle.js"
  },
  resolve: {
    extensions: [ ".ts", ".js" ]
  },
  module: {
    rules: [
      {
        test: 	 /\.js$/,
        loader:  "babel-loader",
        include: APP_DIR
      }, {
        test:    /\.ts$/,
        loader: "awesome-typescript-loader",
        include: APP_DIR,
        options: {
          // NOTE: serves as a handy switch for prototyping needs:
          transpileOnly: true
        }
      }
    ]
  }
};

module.exports = env =>
  env && env.production
  ? merge(commonConfig, {
      mode: "production",
      entry: [
        `${APP_DIR}/index.js` 
      ]
    })
  : merge(commonConfig, {
      mode: "development",
      entry: [
        "webpack/hot/only-dev-server", // Prevents reloading during errors.
        `${APP_DIR}/index.js` 
      ],
      plugins: [
        new webpack.HotModuleReplacementPlugin()
      ]
    });

webpack.config.test.js

let config   = require("./webpack.config"),
    path     = require("path"),
    TEST_DIR = path.resolve(__dirname, "test");

config.entry = [
  `${TEST_DIR}/index.spec.js` 
];

config.module = {
  rules: [
    {
      test:    /\.js$/,
      loader:  "babel-loader",
      include: TEST_DIR
    }, {
      test:    /\.ts$/,
      loader: "awesome-typescript-loader",
      include: TEST_DIR,
      options: {
        // Currently not used, since TS gives a bit of a headache on EcmaNext:
        // NOTE: serves as a handy switch for prototyping needs:
        transpileOnly: true
      }
    }
  ]
};

module.exports = config;
"use strict";

var chai  	   = require("chai"),
    chaiAsPromised = require("chai-as-promised");

chai.use(chaiAsPromised);
chai.should();

(Possibly) relevant libraries in package.json (I haven't omitted the babel-plugins, in case they turn out to be useful in the bug hunt):

"devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@babel/plugin-proposal-do-expressions": "^7.5.0",
    "@babel/plugin-proposal-export-default-from": "^7.5.2",
    "@babel/plugin-proposal-export-namespace-from": "^7.5.2",
    "@babel/plugin-proposal-function-bind": "^7.2.0",
    "@babel/plugin-proposal-function-sent": "^7.5.0",
    "@babel/plugin-proposal-json-strings": "^7.2.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.2.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.4.4",
    "@babel/plugin-proposal-numeric-separator": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.5.5",
    "@babel/plugin-proposal-optional-chaining": "^7.2.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.5.0",
    "@babel/plugin-proposal-throw-expressions": "^7.2.0",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-syntax-import-meta": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "@types/html-webpack-plugin": "^3.2.1",
    "@types/mocha": "^5.2.7",
    "@types/node": "^12.7.3",
    "@types/webpack-env": "^1.14.0",
    "awesome-typescript-loader": "^5.2.1",
    "babel-loader": "^8.0.6",
    "chai": "^4.2.0",
    "chai-as-promised": "^7.1.1",
    "eslint": "^6.3.0",
    "loglevel": "^1.6.3",
    "mocha": "^6.2.0",
    "mochapack": "^1.1.2",
    "sinon": "^7.4.1",
    "typescript": "^3.6.2",
    "webpack": "^4.39.3",
    "webpack-cli": "^3.3.7",
    "webpack-merge": "^4.2.2"
  }

the contents of the file index.spec.js are irrelevant (a file can be empty and the issue will still persist).

Environment if relevant (please complete the following information):

  • OS: Windows 10
  • Node version 8.1.2
  • Mochapack version >=1.1.3
  • Webpack version 4.39.3

Implement --forbid-only

Mocha has an option --forbid-only:
--forbid-only Fail if exclusive test(s) encountered [boolean]

I tried to use it in mochapack by adding that flag to mochapack.opts but I guess it's not implemented yet. Is there any workaround for this?

Add support for --inspect and --inspect-brk options

Mocha supports the --inspect and --inspect-brk options:
--inspect // activate devtools in chrome
--inspect-brk // activate devtools in chrome and break on the first line

It would be helpful if mochapack can pass these options through to mocha.

[Bug] Mocha colors are not visible in v7

  • I'd be willing to submit the fix

posting as a follow up to #53

Describe the bug
colors for mocha tests are not visible from mochapack.

To Reproduce
running any test under the current verison of mochapack shows this behavior

npx mochapack '{test,src}/**/*.test.ts' --watch --clear-terminal

Screenshots
this screenshot shows that 1. errors are not highlighted and and 2. mocha test checkmarks are not highlighted.
screenshot(228)
You can see that webpack specific output (like the compile time) and the final "Tests completed with 1 failure(s)" are highlighted, so colors are working properly in the terminal

Environment if relevant (please complete the following information):

  • OS: Linux
  • Node version v13.8.0
  • Mochapack version v1.1.15
  • Webpack version 4.43.0
  • Mocha version: v7.1.2

Additional context

Add any other context about the problem here.

running mocha on a simple js test without mochapack shows colors being properly displayed, so I am confident this is an issue with how mochapack displays colors
screenshot(230)

[Bug] WebStorm 2020.1 breaks support for running mochapack tests from the IDE

  • I'd be willing to submit the fix

Describe the bug

All mocha test run configurations show an error of "Not found mocha bin file".

To Reproduce

I believe it would happen with any mocha test configured to run in WebStorm.

Screenshots

image

Environment if relevant (please complete the following information):

  • OS: OSX
  • Node version: (All?) 10 and 12
  • Mochapack version: 2.0.0
  • Webpack version: 4.43.0

Additional context

Creating a symlink node_modules/mochapack/bin/mocha to either of the mochapack or _mocha files installed lets the tests run again.

[Feature] Don't clear the console

  • [x ] I'd be willing to implement this feature
  • This feature can already be implemented through a plugin

Describe the user story

I am using my console. It has valuable historical information. Deleting my valuable information is not wanted. Don't clear the console.

Describe the solution you'd like

When I run mochapack, it doesn't clear the console. Rather it just runs in the existing screen as is expected in a Unix-like environment.

Describe the drawbacks of your solution
Some people might like to throw away their console history. While I can certainly see the value in that, most terminals have an option to do that at the user's discretion.

Describe alternatives you've considered
Exploring another package that doesn't clear the console. Forking this repo and removing the clearConsole method form src/runner/testRunnerReporter.js:58 along with all calls to it.

Additional context
It would be reasonable to create this as a option.

--timeout ignored in mochapack.opts

Appending --timeout to the CLI args changes default timeout behavior, but putting the same argument in the mochapack.opts file does not.

Versions:
"mocha": "^7.2.0",
"mochapack": "^2.1.2",
"webpack": "^5.38.1",

Cyclic dependency error

Hi.
Thanks for the fork of mocha-webpack. I'm trying to move my project from webpack 3 to 4 and all works fine except tests. I get this error:

 WEBPACK  Compiled successfully in 66060ms

Error: Cyclic dependency
    at visit (C:\pr\frontend\node_modules\toposort\index.js:35:13)
    at visit (C:\pr\frontend\node_modules\toposort\index.js:53:9)
    at visit (C:\pr\frontend\node_modules\toposort\index.js:53:9)
    at Function.toposort [as array] (C:\pr\frontend\node_modules\toposort\index.js:22:22)
    at sortChunks (C:\pr\frontend\node_modules\mochapack\lib\webpack\util\sortChunks.js:35:41)
    at getBuildStats (C:\pr\frontend\node_modules\mochapack\lib\webpack\util\getBuildStats.js:29:47)
    at TestRunner.prepareMocha (C:\pr\frontend\node_modules\mochapack\lib\runner\TestRunner.js:139:52)
    at C:\pr\frontend\node_modules\mochapack\lib\runner\TestRunner.js:192:38
    at C:\pr\frontend\node_modules\mochapack\lib\webpack\compiler\registerReadyCallback.js:26:7
    at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\pr\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:27:1)
    at AsyncSeriesHook.lazyCompileHook (C:\pr\frontend\node_modules\tapable\lib\Hook.js:154:20)
    at emitRecords.err (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:267:22)
    at Compiler.emitRecords (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:449:39)
    at emitAssets.err (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:261:10)
    at hooks.afterEmit.callAsync.err (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:435:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\pr\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:9:1)
    at AsyncSeriesHook.lazyCompileHook (C:\pr\frontend\node_modules\tapable\lib\Hook.js:154:20)
    at asyncLib.forEachLimit.err (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:432:27)
    at C:\pr\frontend\node_modules\neo-async\async.js:2818:7
    at done (C:\pr\frontend\node_modules\neo-async\async.js:3522:9)
    at MemoryFileSystem.writeFile (C:\pr\frontend\node_modules\memory-fs\lib\MemoryFileSystem.js:328:9)
    at writeOut (C:\pr\frontend\node_modules\webpack\lib\Compiler.js:415:30)
    at Immediate.<anonymous> (C:\pr\frontend\node_modules\memory-fs\lib\MemoryFileSystem.js:288:4)
    at runCallback (timers.js:696:18)
    at tryOnImmediate (timers.js:667:5)
    at processImmediate (timers.js:649:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I found similar issue in html-webpack-plugin jantimon/html-webpack-plugin#981

[Bug] Loaders not being respected

  • I'd be willing to submit the fix

Describe the bug

Loaders (babel and typescript) are not being respected. Although they correctly transpile during build and development. This is at least present on latest versions (tested from 1.1.2 - 1.1.4)

Here's the mumbojambo from terminal. Pretty much just errors caused by missed loaders:

 WEBPACK  Compiling...

  [=========================] 100% (completed)
 WEBPACK  Failed to compile with 7 error(s)

Error in ./test/techniques/functional/monads_level1.spec.ts

  Module parse failed: The keyword 'interface' is reserved (27:4)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |     */
  |     // NOTE: However - Since we R functional AF we have a maker function:
  >     interface Monad<T> {
  |       (value?: T): M<T>
  |     };

Error in ./test/EcmaNext/stage2.spec.js

  Module parse failed: Unexpected token (11:10)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |         \ outside of the constructor:`, function () {
  |       class NewFoo {
  >         x = 0;
  |         incrementX () { this.x++; }
  |         readX ()      { return this.x }

Error in ./test/basics/prototypes.spec.js

  Module parse failed: Unexpected token (133:23)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |         }
  |
  >         boundFunctionB = () => this.instanceProp;
  |       }
  |       let foo = new Foo();

Error in ./test/EcmaNext/stage3.spec.js

  Module parse failed: Unexpected token (21:21)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |       class Foo {
  |         // NOTE: Behaves as before:
  >         instanceProp = "bar";
  |         boundFunction = () => {
  |           return this.instanceProp;

Error in ./test/EcmaNext/stage0.spec.js

  Module parse failed: Unexpected token (21:29)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |       expect(outer.foo()).to.equal(1);
  |
  >       outer.foo = outer.inner::outer.inner.foo;
  |       expect(outer.foo()).to.equal(2);
  |

Error in ./test/EcmaNext/stage1.spec.js

  Module parse failed: Unexpected token (29:12)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |
  |       let qux;
  >       qux ||= bar;
  |       expect(qux).to.equal(1);
  |

Error in ./test/TS/TSTypes.spec.ts

  Module parse failed: Unexpected token (8:21)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |     describe("Booleans:", function () {
  |       it("Forbids the use of other values than 'true/false'", function () {
  >         let isBoolean: boolean = false;
  |         // Compile time error:
  |         // isBoolean = 1;

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `mochapack --webpack-config webpack.config.test.js --require ./test/test_helper.js ./test/index.spec.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] 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:
npm ERR!     C:\Users\Reaper\AppData\Roaming\npm-cache\_logs\2019-09-02T12_15_40_283Z-debug.log

D:\Projects\JavaScript\JS\MasterClass>npm run test

> [email protected] test D:\Projects\JavaScript\JS\MasterClass
> mochapack --webpack-config webpack.config.test.js --require ./test/test_helper.js ./test/index.spec.js
 WEBPACK  Compiling...

  [=========================] 100% (completed)
 WEBPACK  Failed to compile with 7 error(s)

Error in ./test/techniques/functional/monads_level1.spec.ts

  Module parse failed: The keyword 'interface' is reserved (27:4)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |     */
  |     // NOTE: However - Since we R functional AF we have a maker function:
  >     interface Monad<T> {
  |       (value?: T): M<T>
  |     };

Error in ./test/EcmaNext/stage2.spec.js

  Module parse failed: Unexpected token (11:10)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |         \ outside of the constructor:`, function () {
  |       class NewFoo {
  >         x = 0;
  |         incrementX () { this.x++; }
  |         readX ()      { return this.x }

Error in ./test/basics/prototypes.spec.js

  Module parse failed: Unexpected token (133:23)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |         }
  |
  >         boundFunctionB = () => this.instanceProp;
  |       }
  |       let foo = new Foo();

Error in ./test/EcmaNext/stage3.spec.js

  Module parse failed: Unexpected token (21:21)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |       class Foo {
  |         // NOTE: Behaves as before:
  >         instanceProp = "bar";
  |         boundFunction = () => {
  |           return this.instanceProp;

Error in ./test/EcmaNext/stage0.spec.js

  Module parse failed: Unexpected token (21:29)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |       expect(outer.foo()).to.equal(1);
  |
  >       outer.foo = outer.inner::outer.inner.foo;
  |       expect(outer.foo()).to.equal(2);
  |

Error in ./test/EcmaNext/stage1.spec.js

  Module parse failed: Unexpected token (29:12)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |
  |       let qux;
  >       qux ||= bar;
  |       expect(qux).to.equal(1);
  |

Error in ./test/TS/TSTypes.spec.ts

  Module parse failed: Unexpected token (8:21)
  You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
  |     describe("Booleans:", function () {
  |       it("Forbids the use of other values than 'true/false'", function () {
  >         let isBoolean: boolean = false;
  |         // Compile time error:
  |         // isBoolean = 1;

npm ERR! code ELIFECYCLE
npm ERR! errno 1

To Reproduce

To run:

mochapack --webpack-config webpack.config.test.js --require ./test/test_helper.js ./test/index.spec.js

The configuration I have:

babel.config.js

module.exports = function(api) {
  api.cache(true);
  const presets = [
    [ "@babel/preset-env", { 
      "targets": { 
        "browsers": [ "last 2 versions", "> 1%" ],
        "node": "current"
      },
      "modules":     false,
      "useBuiltIns": "entry",
      "debug":       true
    }]
  ];
  const plugins = [
    [ "@babel/plugin-transform-runtime", { "regenerator": true } ],

    // Stage 0
    "@babel/plugin-proposal-function-bind",

    // Stage 1
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-proposal-logical-assignment-operators",
    [ "@babel/plugin-proposal-optional-chaining", { "loose": false } ],
    [ "@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" } ],
    [ "@babel/plugin-proposal-nullish-coalescing-operator", { "loose": false } ],
    "@babel/plugin-proposal-do-expressions",

    // Stage 2:
    [ "@babel/plugin-proposal-decorators", { "legacy": true } ],
    "@babel/plugin-proposal-function-sent",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-numeric-separator",
    "@babel/plugin-proposal-throw-expressions",

    // Stage 3:
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-syntax-import-meta",
    ["@babel/plugin-proposal-class-properties", { "loose": false }],
    "@babel/plugin-proposal-json-strings"
  ];
  return {
    presets,
    plugins
  };
};

webpack.config.js:

const path 	= require("path"),
      webpack 	= require("webpack"),
      merge     = require("webpack-merge"),
      APP_DIR   = path.resolve(__dirname, "src"),
      BUILD_DIR = path.resolve(__dirname, "build");


let commonConfig = {
  target: "node",
  output: {
    path: 	BUILD_DIR,
    publicPath: "/",
    filename: 	"bundle.js"
  },
  resolve: {
    extensions: [ ".ts", ".js" ]
  },
  module: {
    rules: [
      {
        test: 	 /\.js$/,
        loader:  "babel-loader",
        include: APP_DIR
      }, {
        test:    /\.ts$/,
        loader: "awesome-typescript-loader",
        include: APP_DIR,
        options: {
          // NOTE: serves as a handy switch for prototyping needs:
          transpileOnly: true
        }
      }
    ]
  }
};

module.exports = env =>
  env && env.production
  ? merge(commonConfig, {
      mode: "production",
      entry: [
        `${APP_DIR}/index.js` 
      ]
    })
  : merge(commonConfig, {
      mode: "development",
      entry: [
        "webpack/hot/only-dev-server", // Prevents reloading during errors.
        `${APP_DIR}/index.js` 
      ],
      plugins: [
        new webpack.HotModuleReplacementPlugin()
      ]
    });

webpack.config.test.js

let config   = require("./webpack.config"),
    path     = require("path"),
    TEST_DIR = path.resolve(__dirname, "test");

config.entry = [
  `${TEST_DIR}/index.spec.js` 
];

config.module = {
  rules: [
    {
      test:    /\.js$/,
      loader:  "babel-loader",
      include: TEST_DIR
    }, {
      test:    /\.ts$/,
      loader: "awesome-typescript-loader",
      include: TEST_DIR,
      options: {
        // Currently not used, since TS gives a bit of a headache on EcmaNext:
        // NOTE: serves as a handy switch for prototyping needs:
        transpileOnly: true
      }
    }
  ]
};

module.exports = config;

test_helper.js

"use strict";

var chai  	   = require("chai"),
    chaiAsPromised = require("chai-as-promised");

chai.use(chaiAsPromised);
chai.should();

Relevant libraries in package.json:

"devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@babel/plugin-proposal-do-expressions": "^7.5.0",
    "@babel/plugin-proposal-export-default-from": "^7.5.2",
    "@babel/plugin-proposal-export-namespace-from": "^7.5.2",
    "@babel/plugin-proposal-function-bind": "^7.2.0",
    "@babel/plugin-proposal-function-sent": "^7.5.0",
    "@babel/plugin-proposal-json-strings": "^7.2.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.2.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.4.4",
    "@babel/plugin-proposal-numeric-separator": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.5.5",
    "@babel/plugin-proposal-optional-chaining": "^7.2.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.5.0",
    "@babel/plugin-proposal-throw-expressions": "^7.2.0",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-syntax-import-meta": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "@types/html-webpack-plugin": "^3.2.1",
    "@types/mocha": "^5.2.7",
    "@types/node": "^12.7.3",
    "@types/webpack-env": "^1.14.0",
    "awesome-typescript-loader": "^5.2.1",
    "babel-loader": "^8.0.6",
    "chai": "^4.2.0",
    "chai-as-promised": "^7.1.1",
    "eslint": "^6.3.0",
    "loglevel": "^1.6.3",
    "mocha": "^6.2.0",
    "mochapack": "^1.1.2",
    "sinon": "^7.4.1",
    "typescript": "^3.6.2",
    "webpack": "^4.39.3",
    "webpack-cli": "^3.3.7",
    "webpack-merge": "^4.2.2"
  },

Environment if relevant (please complete the following information):

  • OS: Windows 10
  • Node version 10.16.3
  • Mochapack version 1.1.2 - 1.1.4
  • Webpack version 4.39.3

EDIT: I have updated my node but the issue persists. The issue description has been updated accordingly.

A better example please [Feature]

Would it be possible to update the example demonstrating how we can actually test functions loaded from a separate js file via script tag?

Just the basic example... The HTML page imports a script using a script tag. The mocha test script will test/exercise the functions in the external script (the HTML file loads via the script tag). The example provided in the source exercises Mocha but doesn't look as if its testing any functions that would be loaded via script tag.

Thanks for listening!

[Bug] importing of vue.js components

  • I'd be willing to submit the fix

Describe the bug

  1. If I run the test npm run test I get a compilation error. It seams to me that the babel/ES6 is not loaded. I fear that mochapack does not use the webpack configuration :
  "scripts": {
    "build": "webpack --env=dev",
    "buildDev": "webpack --env=dev",
    "buildProd": "webpack --env=prod",
    "test": "mochapack --webpack-env=dev --webpack-config webpack.config.js --require test/setup.js test/**/*.spec.js"
  },
  1. If I remove the component-file ending vue in /test/MyTest.spec.js line 18, I get another error because the file is not found. This seams also to lead to a non complete loading of the webpack configuration of the package (since in my package I can skip the vue ending)

To Reproduce

git clone https://github.com/271ch/fomantic-ui-vue.git
git checkout add-test
npm run test

In /test/MyTest.spec.js, line 18, remove the component-file ending .vue , and then

npm run test

Screenshots

With vue anding:
image

Without vue ending:
image

Environment if relevant (please complete the following information):

  • Linux
  • Node version v10.16.3
  • Mochapack version 1.1.5
  • Webpack version 4.41.0

[Feature] WebStorm testing framework integration

  • I'd be willing to implement this feature

On WebStorm, one can run tests in a .spec.ts file inside the IDE. This provides the advantage of integrating with the existing editor as well as jumping to different parts of the project when some tests inevitably fail.

Currently, WebStorm cannot reliably detect mochapack as a mocha package because of the lack of mocha file in the bin folder. Other mocha replacements, such as electron-mocha can be detected by the IDE. This issue can be solved by either renaming the executable from mochapack to mocha, or symlinking mocha to mochapack in the bin folder.

This fix should fit the ideology of the project better as a drop-in replacement of mocha

[Bug] useColor deprecation warnings with [email protected]

  • I'd be willing to submit the fix

Describe the bug

I am seeing some warnings when running mochapack only visible when using [email protected] and higher. [email protected] and lower do not show it.

> mochapack --interactive=false src/**/*.unit.test.ts

 WEBPACK  Compiling...

 WEBPACK  Compiled successfully in 1170ms

 MOCHA  Testing...



(node:366166) DeprecationWarning: "useColors()" is DEPRECATED, please use "color()" instead.
(node:366166) DeprecationWarning: "useInlineDiffs()" is DEPRECATED, please use "inlineDiffs()" instead.
  src/dsl-parser/__tests__/dsl.unit.test.ts
ran
    ✓ mytest


  1 passing (16ms)

 MOCHA  Tests completed successfully

this does not affect test behavior, but I assume these warnings are because an older mocha color scheme is being used.

To Reproduce

npm install mochapack mocha@7

and run mochapack on any test

  • OS: [e.g. OSX, Linux, Windows, ...] archlinux
  • Node version [e.g. 8.15.0, 10.15.1, ...] v13.8.0
  • Mochapack version [e.g. 1.1.3, ...] 1.1.13
  • Webpack version [e.g. 4.26.1, ...] 4.41.5

Additional context

Public developer api

Hi 👋

Would it be possible to document the api so it is public for developers to use? Maybe even add a *.d.ts file while your at it? I could also do the work for you if you agree.

We of the StrykerMutator team want to support mochapack with mutation testing. For more info see http://stryker-mutator.io.

[Bug] Not able to get --watch to work in examples/debug-webpack4 (or my own project)

  • [ x ] I'd be willing to submit the fix (if I knew how to fix it...)

Describe the bug

I recently tried to switch over a code-base that was using mocha-webpack to use mochapack. I noticed --watch stopped working when I made the switch. In order to double check that the problem wasn't our usage, I cloned the mochapack repo and ran the test loop...all tests passed (including the watch test)...

However, I then opened up the examples/debug-webpack4 folder and ran the test loop in watch mode. Making changes to the index.test.js file did not cause the test loop to re-run.

Now maybe the example just hasn't been updated to account for some change, or maybe there is an actual bug - I'm not really sure.

To Reproduce

  1. checkout master (git sha 7d0cbaf at time of filing)
  2. Run cd examples/debug-webpack4 && npm i && npm run test:watch
  3. Observe that test loop runs successfully and waits
  4. Open up the file examples/debug-webpack4/src/__tests__/index.test.js and make a change to it
  5. Observe that the test loop DOES NOT re-run.

Environment if relevant (please complete the following information):

  • OS: OSX 10.14.16
  • Node version: 11.9.0
  • Mochapack version: git sha 7d0cbaf (master at time of filing

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.