Skip to content
On this page

Testing framework:

MochaJS is one of the most popular JavaScript testing frameworks. It operates on Node.js and provides front-end and back-end asynchronous testing compatibility.

Example of testing with Mocha

  • test.specs.js
js
const { describe, it } = require('mocha');
const { assert } = require('chai');

function sum(a,b) {
    return a+b;
}
describe('sum(a,b)', function() {
  it('should return 6 for sum(1,5)', function() {
    assert.equal(sum(1,5), 6);
  });
});
1
2
3
4
5
6
7
8
9
10
11

Examples of unit testing frontend challenges

  • VueComponent.vue
html
<template>
    <h1>
        Hello World
    </h1>
    </template>
    <script>
    export default {
        setup() {
            return {}
        }
    }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
  • test.specs.js
js
import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';

import VueComponent from './VueComponent.vue';

describe('VueComponent.vue', function() {
    let wrapper;
    let h1;
    beforeEach(function() {
        wrapper = shallowMount(VueComponent);
        h1= wrapper.find('h1');
    });
    it("Displays a button with the text 'Show More'", function() {
        expect(button.text()).to.equal('Hello World');
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Test Framework for JavaScript

  • Testing rendered text
js
describe('TodoItem.vue', function() {
  // testing DOM content
  it('should display title inside ToDo item', function() {
    expect(component.find('a span').text()).to.equal('My title');
  });
});
1
2
3
4
5
6
  • Test DOM attributes
js
describe("TodoItem.vue", function() {
// testing DOM attributes
  it("should set the title attribute of the Todo item", function() {
    expect(component.find('a').attributes().title === 'My title').to.be.true;
  });
});
1
2
3
4
5
6
  • Test using find/findAll
js
// testing todo items are rendered
it("should render a list of Todo items", function() {
  const items = component.findAllComponents({ name: "TodoItem" });
  expect(items).to.have.length(2);
});
1
2
3
4
5
  • Test props
js
expect(component.find('span').text()).to.equal(props.item.title);
1
  • Test element classes
js
describe("ProgressBar.vue", () => {
  it("is hidden on initial render", () => {
    const wrapper = shallowMount(ProgressBar);
    expect(wrapper.classes()).toContain("hidden");
  });
});
1
2
3
4
5
6
  • Test style
js
it("should have Todo item inactive width equal prop value", function() {
  const todoElem = component.find("[data-test-id='todo-item']").element;
  expect(todoElem.style.width).to.be.equal(`${props.inactiveWidth}px`);
});
1
2
3
4

Test route changing

js
import { mount } from "@vue/test-utils";
import { expect } from 'chai';
import { createRouter, createWebHistory } from 'vue-router';

import App from './App.vue';
import HomePage from './HomePage.vue';
import AboutPage from './AboutPage.vue';

describe('App.vue', () => {
  it('renders Home page by default', async () => {
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        {
          path: '/',
          name: 'home',
          component: HomePage
        },
        {
          path: '/about',
          name: 'about',
          component: AboutPage
        },
        {
          path: '/context.html',
          name: 'context',
        }
      ]
    });

    const wrapper = mount(App, {
      global: {
        plugins: [router],
        mocks: {
          $route: {
            path: '/'
          }
        }
      }
    });

    await router.push('/');

    expect(wrapper.findComponent(HomePage).exists()).to.be.true;
    expect(wrapper.findComponent(AboutPage).exists()).to.be.false;
  });

  it('renders About page on route change', async () => {
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        {
          path: '/',
          name: 'home',
          component: HomePage
        },
        {
          path: '/about',
          name: 'about',
          component: AboutPage
        },
        {
          path: '/context.html',
          name: 'context',
        }
      ]
    });

    const wrapper = mount(App, {
      global: {
        plugins: [router],
      }
    });

    await router.push('/about');

    expect(wrapper.findComponent(HomePage).exists()).to.be.false;
    expect(wrapper.findComponent(AboutPage).exists()).to.be.true;
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

Test mocking http requests for Node.JS challenges.

  • index.js
js
const axios = require('axios');

async function submitName(name) {
  const response = await axios.post('/api/submit', { name });
  return response.data;
}

module.exports = {
  submitName
}
1
2
3
4
5
6
7
8
9
10
  • index.specs.js
js
const sinon = require('sinon');
const axios = require('axios');
const { describe, it, beforeEach, afterEach } = require('mocha');
const { expect } = require('chai');

const { submitName } = require('./index.js');

describe("index.js", function() {
  let axiosPostStub;

  beforeEach(() => {
    axiosPostStub = sinon.stub(axios, 'post');
  });

  afterEach(() => {
    axiosPostStub.restore();
  });

  it('sends a POST request to /api/submit with name', async () => {
    const expectedData = { foo: 'bar' };
    axiosPostStub.resolves({ data: expectedData });

    const result = await submitName('John Doe');

    sinon.assert.calledOnceWithExactly(axiosPostStub, '/api/submit', { name: 'John Doe' });

    expect(result).to.deep.equal(expectedData);
  });

  it('handles a successful request with a non-JSON response', async () => {
    const expectedData = 'Hello, world!';
    axiosPostStub.resolves({ data: expectedData });

    const result = await submitName('John Doe');

    sinon.assert.calledOnceWithExactly(axiosPostStub, '/api/submit', { name: 'John Doe' });

    expect(result).to.deep.equal(expectedData);
  });

  it('handles a successful request with a JSON response', async () => {
    const expectedData = { message: 'Success!' };
    axiosPostStub.resolves({ data: expectedData });

    const result = await submitName('John Doe');

    sinon.assert.calledOnceWithExactly(axiosPostStub, '/api/submit', { name: 'John Doe' });

    expect(result).to.deep.equal(expectedData);
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

Test mocking http requests for Vue.

  • BaseForm.vue
html
<template>
  <form @submit.prevent="submitForm">
    <label>
      Name:
      <input type="text" v-model="name">
    </label>
    <button type="submit">Submit</button>
  </form>
</template>

<script setup>
import axios from 'axios';
import { ref } from "vue";

const name = ref('');
const submitForm = async () => {
  try {
    const response = await axios.post('/api/submit-form', { name: name.value });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  • BaseForm.specs.js
js
import sinon from 'sinon';
import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';

import BaseForm from './BaseForm.vue';

describe('BaseForm.vue', function() {
  let server;
  let wrapper;

  beforeEach(() => {
    server = sinon.fakeServer.create();

    wrapper = shallowMount(BaseForm, {});
  });

  afterEach(() => {
    server.restore();
  });

  it('submits the form', async () => {
    const response = { data: 'Success!' };
    server.respondWith('POST', '/api/submit-form', [
      200,
      { 'Content-Type': 'application/json' },
      JSON.stringify(response),
    ]);

    const input = wrapper.find('input[type="text"]');
    const form = wrapper.find('form');

    await input.setValue('John Doe');
    await form.trigger('submit');

    expect(server.requests.length).to.equal(1);
    expect(server.requests[0].method).to.equal('POST');
    expect(server.requests[0].requestBody).to.equal('{"name":"John Doe"}');
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

Test file system challenges in Node.JS.

  • index.js
js
const fs = require("fs");

const files = [
  { name: "file1.txt", content: "This is the content of file 1" },
  { name: "file2.txt", content: "This is the content of file 2" },
  { name: "file3.txt", content: "This is the content of file 3" },
];

async function createFiles() {
  for(const file of files) {
    await fs.promises.writeFile(file.name, file.content);
    console.log(`${file.name} has been created with the following content: ${file.content}`);
  }
}

async function printFileContents() {
  for(const file of files) {
    const data = await fs.promises.readFile(file.name, "utf8");
    console.log(`${file.name} contains the following content: ${data}`);
  }
}

module.exports = {
  createFiles,
  printFileContents,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  • index.specs.js
js
const sinon = require('sinon');
const { describe, it, beforeEach, afterEach } = require('mocha');
const { assert } = require('chai');
const fs = require('fs');

const { createFiles, printFileContents } = require('./index.js');

describe('fileOperations', () => {
  let clock;

  beforeEach(() => {
    clock = sinon.useFakeTimers();
  });

  afterEach(() => {
    clock.restore();
  });

  describe('createFiles', () => {
    beforeEach(() => {
      if (fs.existsSync('file1.txt')) {
        fs.unlinkSync('file1.txt');
      }
      if (fs.existsSync('file2.txt')) {
        fs.unlinkSync('file2.txt');
      }
      if (fs.existsSync('file3.txt')) {
        fs.unlinkSync('file3.txt');
      }
    });

    it('should create the files with the specified names and contents', async () => {
      return new Promise(async (resolve) => {
        await createFiles();

        clock.tickAsync(1000);

        setTimeout(() => {
          assert(fs.existsSync('file1.txt'), 'file1.txt should exist');
          assert(fs.existsSync('file2.txt'), 'file2.txt should exist');
          assert(fs.existsSync('file3.txt'), 'file3.txt should exist');
          assert.strictEqual(fs.readFileSync('file1.txt', 'utf8'), 'This is the content of file 1', 'file1.txt should contain the expected content');
          assert.strictEqual(fs.readFileSync('file2.txt', 'utf8'), 'This is the content of file 2', 'file2.txt should contain the expected content');
          assert.strictEqual(fs.readFileSync('file3.txt', 'utf8'), 'This is the content of file 3', 'file3.txt should contain the expected content');

          resolve();
        }, 1000);
      });
    });
  });

  describe('printFileContents', () => {
    it('should print the contents of the files', () => {
      return new Promise(async (resolve) => {
        const logSpy = sinon.spy(console, 'log');

        await printFileContents();

        clock.tickAsync(1000);

        setTimeout(() => {
          assert(logSpy.calledWith('file1.txt contains the following content: This is the content of file 1'), 'file1.txt content should be printed');
          assert(logSpy.calledWith('file2.txt contains the following content: This is the content of file 2'), 'file2.txt content should be printed');
          assert(logSpy.calledWith('file3.txt contains the following content: This is the content of file 3'), 'file3.txt content should be printed');

          logSpy.restore();
          resolve();
        }, 1000);
      });
    });
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72