mardi 28 juillet 2020

Jasmine Testing: Spy.and.returnValue() not working

I'm trying to implement tests for my javascript using Jasmine, but I'm running into some problems with .and.returnValue. This is my test:

describe("Test the ResultsPage Function", () => {
let dummyContainer;
let htmlResponse;
let htmlCode;

beforeEach(() => {
    console.log("Before Each is Running");
    htmlResponse = new Response('<div><h id="pick"></h><h1 id="rating"></h1><div id="photo"></div></div>');
    htmlCode = '<div><h id="pick"></h><h1 id="rating"></h1><div id="photo"></div></div>';
    spyOn(window, 'resultsPage').and.callThrough();
    dummyContainer = document.createElement('div');
    spyOn(document, 'getElementById').withArgs('page-container').and.returnValue(dummyContainer);
    console.log("Spy Made");
    console.log(document.getElementById("page-container"));
    spyOn(window, 'loadImage');
    spyOn(window, 'fetch').and.returnValue(Promise.resolve(htmlResponse));
});

it("Test that the function runs correctly", () =>{
    resultsPage("restaurant", "5", "https://www.w3schools.com/images/lamp.jpg");
    expect(fetch).toHaveBeenCalledWith("../results.html");
    expect(resultsPage).toHaveBeenCalled();
});

it("Test that the function alters the DOM correctly", () =>{
    console.log("Test is running")
    resultsPage("restaurant", "5", "https://www.w3schools.com/images/lamp.jpg");
    expect(fetch).toHaveBeenCalledWith("../results.html");
    expect(resultsPage).toHaveBeenCalled();
    expect(dummyContainer.innerHTML).toEqual(htmlCode);
});

});

And this is the function I am trying to test:

function resultsPage(name, rating, photoUrl) {
fetch(`../results.html`)
    .then((html) => html.text())
    .then((html) => {
        let temp = document.getElementById("page-container");
        console.log(temp);
        document.getElementById("page-container").innerHTML = html;
        document.getElementById("pick").innerText = name;
        document.getElementById("rating").innerText = rating;
        loadImage(photoUrl);
    });

}

I added the log statements to verify the behavior of the test as it progresses and I can see that when 'document.getElementById("page-container")' is called in the beforeEach, it correctly returns the spy. However, when it is run in the resultsPage function itself, it only returns null Console Print Statements Any reason that the .and.returnValue() behavior is not working?

Aucun commentaire:

Enregistrer un commentaire