Setup
Marko Testing Library
is not dependent on any test runner. However, it is
dependent on the test environment. This package works for testing both server
side, and client-side Marko templates and provides a slightly different
implementation optimized for each. This is done using a
browser shim,
just like in Marko.
The browser shim is picked up by many tools, including all bundlers and some test runners.
Below is some example configurations to test both server and browser components with some popular test runners.
Jest
For Jest to understand Marko templates you must first install the @marko/jest preset. This allows your Marko templates to be imported into your tests.
In Jest there is a browser option which will tell Jest to resolve the browser shim version of all modules as mentioned above.
To test components rendered on the client-side, be sure to enable both the
browser
option and the preset and you are good to go!
module.exports = {
preset: '@marko/jest/preset/browser',
}
For testing components rendered on the server-side we can instead use
@marko/jest/preset/node
as our jest preset.
module.exports = {
preset: '@marko/jest/preset/node',
}
A Jest configuration can also have multiple projects which we can use to create a combined configuration for server-side tests, and client-side tests, like so:
module.exports = {
projects: [
{
displayName: 'server',
preset: '@marko/jest/preset/node',
testRegex: '/__tests__/[^.]+\\.server\\.js$',
},
{
displayName: 'browser',
preset: '@marko/jest/preset/browser',
testRegex: '/__tests__/[^.]+\\.browser\\.js$',
},
],
}
Mocha
Mocha also works great for testing Marko components. Mocha, however, has no understanding of browser shims which means out of the box it can only work with server-side Marko components.
To run server-side Marko tests with mocha
you can simply run the following
command:
mocha --require marko/node-require
This enables the Marko require hook and allows you to require server-side Marko templates directly in your tests.
For client-side testing of your components with Mocha often you will use a bundler to build your tests (this will properly resolve the browser shims mentioned above) and then you can load these tests in some kind of browser context.