简体   繁体   中英

How to setup mocha to run tests in a Gatsby repo

I'm trying to get tests to run in a gatsby repo using Mocha, because we already have a lot of tests using mocha and chai, and we don't want to have 2 different assertion libraries, so we're not using Jest.

The first thing I did, is this:

npm i -D mocha chai @testing-library/react

Which installs mocha v8 and chai v4, Then I add a naive script in my package.json to see what happens:

"scripts": {
  "test": "mocha --watch"
}

This gives me an error: unexpected token import for import { expect } from 'chai'; in my bare-bones test file. So next step, following Gatsby's conventions:

"scripts": {
  "test": "npx --node-arg '-r esm' mocha --watch"
}

Okay, we're live, but no tests are running, next iteration:

"scripts": {
  "test": "npx --node-arg '-r esm' mocha --watch 'src/**'"
}

Alright, now it crashes because of SyntaxError: Invalid or unexpected token for a <div> in a react component file.

At this point, I wonder if I really have to install babel and all of its machinery just to run a simple test, especially since gatsby does not use babel at all?

Does someone know of a really clean, modern setup that makes writing tests with mocha in Gatsby simple? Can esm be taught to read JSX without a pile of hacks?

At this point, I wonder if I really have to install babel and all of its machinery just to run a simple test

Unfortunately, yes.

, especially since gatsby does not use babel at all?

Actually that's not true, it's babel all the way down.


Thankfully, since Gatsby has already done all the tedious work of setting up babel, it's rather easy to set up your tests.

First, install the missing bits:

npm i -D @babel/register jsdom jsdom-global

Then add a fresh .babelrc at the root of the project with the following config:

{
  "presets": ["babel-preset-gatsby"]
}

You don't need to install babel-preset-gatsby since it comes with all Gatsby setup.

That should be it. Now replace esm with @babel/register & register jsdom-global . Also make sure you set your NODE_ENV to test :

NODE_ENV=test npx mocha -r @babel/register -r jsdom-global/register ./src/**/*.test.js

And that should work.


When you add the test command to package.json , no needs to use npx:

"scripts": {
  "test": "NODE_ENV=test mocha -r @babel/register -r jsdom-global/register ./src/**/*.test.js"
}

If you're testing Gatsby components, here's a few global variables you need to watch out for: __PATH_PREFIX__ , __BASE_PATH__ , and ___loader .

Mock them however you'd like, but for a quick and dirty test:

globalThis.__PATH_PREFIX__ = '/'
globalThis.__BASE_PATH__ = './'
globalThis.___loader = { enqueue: () => {} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM