import {test} from 'node:test';
import assert from 'node:assert/strict';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Board from './main.jsx';
const labels = () => screen.getAllByRole('button').map((button) => button.textContent);
const status = () => screen.getByText(/^(Next player|Winner):/).textContent;
const play = async (user, squares) => {
for (const i of squares) await user.click(screen.getAllByRole('button')[i]);
};
test('X and O take turns', async () => {
const user = userEvent.setup();
render(<Board />);
await play(user, [0, 1, 2]);
assert.deepEqual(labels().slice(0, 3), ['X', 'O', 'X'], 'after three moves the top row reads ' + JSON.stringify(labels().slice(0, 3)));
assert.equal(status(), 'Next player: O', 'after three moves the status reads ' + JSON.stringify(status()));
});
test('A filled square does not change', async () => {
const user = userEvent.setup();
render(<Board />);
await play(user, [4, 4]);
assert.equal(labels()[4], 'X', 'after two clicks on the middle square it shows ' + JSON.stringify(labels()[4]));
assert.equal(status(), 'Next player: O', 'a click on a filled square must not pass the turn; the status reads ' + JSON.stringify(status()));
});
test('Three in a row shows the winner', async () => {
const user = userEvent.setup();
render(<Board />);
await play(user, [0, 3, 1, 4, 2]);
assert.equal(status(), 'Winner: X', 'after X fills the top row the status reads ' + JSON.stringify(status()));
});
test('No moves after a win', async () => {
const user = userEvent.setup();
render(<Board />);
await play(user, [0, 3, 1, 4, 2, 8]);
assert.equal(labels()[8], '', 'after the win a click on the last square shows ' + JSON.stringify(labels()[8]));
});
test('React prints no warnings', async () => {
const warnings = [];
const original = console.error;
console.error = (...args) => warnings.push(args.join(' '));
try {
const user = userEvent.setup();
render(<Board />);
await user.click(screen.getAllByRole('button')[0]);
} finally {
console.error = original;
}
assert.deepEqual(warnings, [], 'console.error while rendering and clicking');
});