I want to write a unit test for the function renderSetupPage
with Vitest. Somthing with the mocked function startGame
seems to be wrong, but I can’t find the error.
../scripts/utils.js
:
export const renderSetupPage = (container) => {
// create parent element
const div = document.createElement("div")
div.innerHTML =
`
<label for="seed">Seed:</label>
<input type="text" id="seed" name="seed">
`
// create button
const button = document.createElement("button")
button.id = "start-game-button"
button.innerText = "Start Game"
button.onclick = ()=> startGame()
// append to parent
div.appendChild(button)
container.appendChild(div)
}
export const startGame = () => {
window.alert("game started")
}
utils.test.js
:
import { test, expect, vi, describe } from "vitest";
import * as utils from '../scripts/utils';
import {JSDOM} from "jsdom"
describe.only("that setup page is build correctly", ()=>{
const dom = new JSDOM("<div id='container'></div>")
global.document = dom.window.document
const container = document.getElementById("container")
utils.renderSetupPage(container)
const button = container.getElementsByTagName("button")
// passes
test("that create button exists",() => {
expect(button.length).toBe(1)
expect(button[0].id).toBe("start-game-button")
})
// fails
test("that button click starts game",()=>{
const startGameSpy = vi.spyOn(utils, 'startGame').mockImplementation(()=>{})
button[0].click()
expect(startGameSpy).toHaveBeenCalled()
})
})
The tests returns:
Error: AssertionError: expected "startGame" to be called at least once
which shouldn’t be correct since a click in browser gives me the “Game started” alert.