mardi 16 juin 2020

Trying to test fetch with mocha & chai using await

I intend to test fatch with mocha. I am using testing fetch with mocha and chai to get started but kept running into multiple errors. Not sure what I am doing wrong.

Here is the test code:

var jsdom = require('mocha-jsdom')
global.document = jsdom();
const chai = require( 'chai' ).assert;
const fetch = require("node-fetch");
const chaiHTTP = require("chai-http");
const index = require('../client/js/index');

chai.should();
chai.use(chaiHTTP)

described('Index', function(){
  jsdom()
  it( "sends a fetch request", async () =>{
      // chai.request(index)
        await fetch("https://anapioficeandfire.com/api/books")
        .then((res) => {
            return res.json()
        })
        .then((res) => {
            console.log(res);
            assert.equal(res, true)
        })
  })
})

This throws the following error :

    TypeError: Cannot read property 'querySelector' of undefined
//index.js
function fetchBooks(){
  fetch(`https://anapioficeandfire.com/api/books`)
    .then(res => res.json())
    .then(renderBooks)
}

const main = document.querySelector('#main')
function renderBooks(data) {
  data.forEach(book => {
    h2.innerHTML = `<h2>${book.name}</h2>`
  })
}

Aucun commentaire:

Enregistrer un commentaire