CPSC270
Software Engineering and Project Design

Activity 28

Testing - Jest Mock

The following class uses the node-fetch package to get get data via the Wikipedia API.

const fetch = require('node-fetch');

class Article {
  constructor(title) {
    this._title = title.replace(' ', '_');
  }

  async _fetchJson() {
    if (!this._json) {
      const response = await fetch(`http://en.wikipedia.org/w/api.php?action=query&prop=info&format=json&titles=${this._title}`);
      const data = await response.json();
      this._json = data;
    }
    return this._json;
  }

  async getLanguage() {
    const json = await this._fetchJson();
    if (!json) {
      throw new Error(`Error fetching ${this._title}`);
    }
    const pages = Object.keys(json.query.pages);
    if (!pages || pages.length === 0) {
      throw new Error(`Error fetching ${this._title}`);
    }
    return json.query.pages[pages[0]].pagelanguage;
  }
}

module.exports = Article;

The Wikipedia API returns JSON with information about an article. For example, the Wikipedia article on ‘JavaScript’ information is:

{
  batchcomplete: '',
  query: {
    pages: {
      '9845': {
        pageid: 9845,
        ns: 0,
        title: 'JavaScript',
        contentmodel: 'wikitext',
        pagelanguage: 'en',
        pagelanguagehtmlcode: 'en',
        pagelanguagedir: 'ltr',
        touched: '2021-04-16T15:06:33Z',
        lastrevid: 1017870878,
        length: 72024
      }
    }
  }
}

Write Jest tests for the getLanguage method that mocks the node-fetch package. The package’s fetch function returns an object with a method called json that returns the fetched JSON object. For the Article class, the JSON object will contain data like the above Wikipedia example.