Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Structured JavaScript test cases, inspired by Spock Framework

License

NotificationsYou must be signed in to change notification settings

spockjs/spockjs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Structured JS test cases, inspired bySpock Framework

build statusAppVeyor build statuscode coverage

npm packagelicense

Note: This project is in an early stage of development and currently providesonly a small set of features.

Example test case

test('basic arithmetic',()=>{  expect:{1+2===3;3*3>=4*4;// falsy}});
(3 * 3 >= 4 * 4) is not truthy   # test.js:4  _assert(3 * 3 >= 4 * 4, "(3 * 3 >= 4 * 4) is not truthy")            |   |    |            |   |    16            9   false

Installation

npm install --save-dev @spockjs/babel-plugin-spock power-assert

This project is aBabel plugin that needs to transformyour test sources in order to generate assertions, so your test runner will needsupport for Babel. Babel integrates quite nicely into most modern test runners.Check the documentation of your test runner for instructions on how to configureBabel (e.g. forJest,AVA etc.)or consult Babel's owndocumentation.

Once Babel is set up for your test files, simply add"@spockjs/babel-plugin-spock"to theplugins array in your babel configuration and you're good to go.If you do not already use ES modules via Babel,you will also need to set up Babel for transforming ES2015 imports (usually via@babel/preset-env) so the assert helpers can be imported automatically.

Note: This plugin requires Babel 7. Babel 6 is no longer supported.

TypeScript

It is possible to use this plugin with TypeScript,but only if you compile the TypeScript code with Babel (@babel/preset-typescript).The official TypeScript compiler (tsc) is not supported.

Test runners

The plugin should work with all test runners by default(perhaps with occasional config tweaks to the runners).You can take a look atour integration teststo see how we configured each runner that is tested.

Nevertheless, we provide additional tweaks and featuresto improve the experience with some popular test runners.If your runner appears in the list below, it is recommendedyounpm install --save-dev the corresponding package andadd it to thepresets in the plugin'sconfig filefor a flawless experience.

Jest

Package:@spockjs/preset-runner-jest

Currently provides

  • assertion messages that show what went wrong

AVA

Package:@spockjs/preset-runner-ava

Currently provides

  • internal use of native AVA assertions
    • no need to configure"failWithoutAssertions": false
    • assertion errors look just like in regular AVA

Peculiarities:

  • AVA'st must be available in the test cases;using a different name for the test case parameter is not currently supported.If you do not follow this convention in all your test cases,you will have to disable@spockjs/preset-runner-ava anduse the "vanilla" spockjs with its disadvantages.

Usage

Assertion blocks

Inside of a block labeled withexpect: orthen:, all statements will beconsidered assertions and evaluated to check for truth:

expect:{1<2;}

when-then blocks can be particularly useful and expressive for code withside effects:

// The 'when' label here does not have a special meaning// It is used simply to make the test more structuredwhen:{abc.setXyz(1);}then:{abc.getXyz()===1;}

Single labeled statements are also possible:

expect:'a'+'b'==='ab';

Note that these blocks can only contain statements that can be evaluated asexpressions. For example, an if statement would not be valid:

// BADexpect:{if(x<1)x===0.5;elsex===2;}

However, you can nest an assertion block into other structures:

// GOODif(x<1) expect:x===0.5;else expect:x===2;

If you want to perform more complicated checks, it might be helpful to look forsmall helper libraries on npm. For example,deep-strict-equal can helpperform deep equality checks on object structures. In the future, this pluginmight provide special syntax for such use cases.

Of course, you still have the option to use your native assertion libraryalongside assertion blocks wherever you consider it appropriate.Some assertion libraries may provide features on top of what this plugin supports.

Linters

The test you will write using this plugin often employ syntax that is otherwiseuncommon in JavaScript code. For this reason, if you use a linter such asESLint, you will likely see annoying warnings all overyour tests. To work around this, most linters will give you multiple options:

  • Disable the problematic rules with special annotations in your test files.This can be a hassle because it needs to be done for every file.
  • Completely disable the rules in the configuration. This means that they willno longer apply to production code either.
  • Create a separate config for tests that extends the base config, but disablesthe rules.

If you're using TypeScript, tsc might also complain about unused labels.allowUnusedLabels can turn those warnings off.

Configuration

You can configure this plugin using Babel's regularplugin configuration mechanism.The following options are available:

powerAssert

The plugin can seamlessly generate assertions that produce detailed mismatchmessages to help you figure out what exactly about the assertion went wrong.Turning this feature off could be useful if you're tests appear to run slowly oryou are experiencing other issues with your assertions.

This feature is powered by the awesome projectpower-assert.

type:boolean
default:true

autoImport

The plugin transforms your assertion blocks to calls to an assert function.By default (true), this function is automatically imported frompower-assert.You can set this option to a string containing the name of a modulethat exports an assert function as its default exportto use that module for assertions instead.

You can also set this option tofalse to disable automatic imports.You will then have to provide a function namedassert yourselfin your test files wherever you use assertion blocks.

type:boolean | string
default:true ('power-assert')

staticTruthCheck

The plugin can try to statically evaluate your assertion expressions at compile-timeand throw an error if they can be inferred to always be truthy or to always be falsy.Such expressions sometimes indicate a test that does not provide any value.

Here's an example of an assertion expression that can be inferred to always be truthy:

constx=1;expect:x===1;

type:boolean
default:false

assertFunctionName

The plugin will automatically define an assert import or use an existing one.You can set this option to enforce a specific name for the generated assert calls.

type:string
default: empty string (generated identifier)

presets

Presets are collections of additional features or behavior tweaks for the plugin.The plugin will import modules with the exact names specified in this array and use them as presets.SeeTest runners for some presets provided by spockjs itself.

To implement your own preset, take a look at one of the@spockjs/preset-* packages.The exports of a preset module must match theHooks type defined by@spockjs/config.

type:string[]
default:[]

Escape route

In case you wish to stop using this plugin at some point,but of course don't want to rewrite all of your tests manually,there is always an escape hatch available.We also have anintegration testto safeguard this possibility.

Codemod configuration

Create aconfig.json:

{"plugins": [    ["@spockjs/babel-plugin-spock",      {"powerAssert":false,"autoImport":"assert","assertFunctionName":"assert"      }    ]  ]}

Explanation

We turn offpowerAssert because it generates a lot of unreadable code.
We setautoImport toassert instead of the defaultpowerAssertto also switch back to the native nodeassert moduleas we move away from the plugin.
We set theassertFunctionName toassertto avoid auto-generated identifiers in our tests.Note that you must ensure your testsdo not declare anassert identifier themselvesto avoid a potential collision.

Running the codemod

To transform a test file with Babel andoverwrite it immediately, execute

npx --no-install babel --no-babelrc --config-file ./config.json \your-test-file.js --out-file your-test-file.js

npx --no-install babel executes your local (package-wide) Babel installation.If you do not have@babel/cli installed locally,you can alsonpm install -g @babel/core @babel/cli it globally.The--no-babelrc and--config-file Babel options ensure thatwe only apply exactly the changes from the plugin.

You can also use Babel to apply the changes to an entire folder of tests:npx [...] tests --out-dir tests

About

Structured JavaScript test cases, inspired by Spock Framework

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp