# Writing Unit Tests for Magnolia CMS JavaScript Models with Jest

# Introduction

Magnolia JavaScript models allow you to write custom Magnolia functionality without the hassle and weight of a Java Maven module. This guide will teach you how write unit tests for JavaScript models with the Jest testing framework.

See magnolia-cms-javascript-model-unit-test-demo for a fully functional Yarn project based on this guide.

# Prerequisites

  1. You've created a Magnolia JavaScript model
  2. You have experience with the Yarn or NPM package managers
  3. You have experience with Jest and have it installed in your project

# Step 1—Installing babel-plugin-rewire

In order to write tests for Magnolia JavaScript models, install and setup the babel-plugin-rewire plugin. Otherwise, you'll encounter the following error.

TypeError: Model is not a constructor

This is because Jest can't access Magnolia JavaScript model private variables by default. See How to run Jest tests with Rewire plugin for more info.

# Step 2—Writing the Test

We'll write a test for the follow example model.

var Model = function() {
  this.feedCows = function() {
    return 'Cows have been fed';

new Model();

To write a test, use the __get__ method babel-plugin-rewire provides.

describe('feedCows', () => {
  it('should return reduced list', () => {
    const Model = require('model.js').__get__('Model');
    const model = new Model();

    expect(model.feedCows()).toEqual('Cows have been fed');

Now you can access all the fields on the model's main object and test as you please.