How to write tests for Yeoman generator.

Image source:

First of all, let’s take a look at the Yeoman official documentation. I don’t know how about you, but for me it gives basic information about the core things, but it isn’t very helpful.
Well, I like tutorials or guides where I can see the entire thing, or, should I say, the context.

The generator

I am going to write tests for my simple-react-component generator, which creates functional or class React component depends on user choose. It also creates boilerplate for components’ tests.
You can look at final test file if you want.


First, we need to install Mocha test framework, yeoman-test and yeoman-assert as dev dependencies.
We want to store all of our tests in one place, so let’s create a folder on project root level and name it “tests”.
In my generator, I’ve decided to have only one file, the “” where I put all of the major scenarios.

Run the generator in the sandbox

First of all, we need to run our generator and test (assert) the output which, in this case, in a React component.
The best way to do this is to mock and run the generator within Mocha’s beforeEach hook:

What does the code do? Let’s analyse it line by line:, ‘../generators/app’))

mocks the generator (I use here “path” library from node js core);

.inDir(path.join(__dirname, ‘tmp’))`

creates a directory where generator will copy the template. It’s equivalent of real project directory;

name: componentName,
type: ‘Functional’

mocks (simulate) the prompts which are normally filed/selected by the user on the command line.
Because this is only temporary directory we want to remove it after assertions. We can do this in another hook called “”:

afterEach(() => {
rimraf.sync(path.join(__dirname, ‘tmp’));

Note, that I use here funny library, rimraf, which does nothing else than

Test scenario: Create component with given name

Finally, it’s time to write some tests! And we use for the first time! Yo Yo Yo!
I want to check if component created by generator has a name given by the user.


Test scenario: Replace the template name with given component name in files

The second scenario is for ensure us that the generator changed the template name to the name given by user within the component file:

`const ${componentName}`

We can add here more assertions to check all occurrences of the template name in the “generated” files, but this one above is a required minimum.

As I sad at the beginning of this article, the best way to understand what I wrote here is to look at final test.

If something is unclear to you, let me know in comments below. Keep testing! Yo!

Agile Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store