In attempting to mock a Math.floor call in Vitest, the test ends up raise an error:
- TypeError: Cannot read properties of undefined (reading ‘value’)
This error is raised on the following line: expect(mock_floor.mock.results[0].value).toBe(1);
test("test that a quote is returned from an Array of quotes", () => {
const quotes = [{"character": "Me", "quote": "Hi"}, {"character": "You", "quote": "Bye"}];
const mock_floor = vi.spyOn(Math, "floor");
mock_floor.mockReturnValue(1);
const quote = generate_quote(quotes);
expect(mock_floor.mock.results[0].value).toBe(1);
expect(quote).toEqual({"character": "You", "quote": "Bye"});
});
function generate_quote(quotes) {
return quotes[Math.floor(Math.random() * quotes.length + 1)]
}
I’ve discovered that mock_floor.mock.results
returns an empty array. Why would this be? When the aforementioned expect statement is commented out the test will pass with the subsequent expect statement: expect(quote).toEqual({"character": "You", "quote": "Bye"});
.