Fix/refactor tests

This commit is contained in:
Catalin Constantin Mititiuc 2025-06-16 22:41:31 -07:00
parent dac61e6121
commit c46c361217
15 changed files with 160 additions and 135 deletions

View File

@ -155,9 +155,6 @@ const resolveSvgImports = {
name: 'resolveSvgImports', name: 'resolveSvgImports',
setup(build) { setup(build) {
build.onStart(() => { build.onStart(() => {
console.log("BUILD STARTED");
console.log(build.initialOptions.outdir);
fs.rmSync(path.resolve(build.initialOptions.outdir), { recursive: true, force: true }); fs.rmSync(path.resolve(build.initialOptions.outdir), { recursive: true, force: true });
}); });
@ -228,7 +225,6 @@ const ctx = await esbuild.context({
'.svg': 'file' '.svg': 'file'
}, },
assetNames: 'assets/images/[name]-[hash]', assetNames: 'assets/images/[name]-[hash]',
metafile: true
}); });
await ctx.watch(); await ctx.watch();

View File

@ -6,4 +6,7 @@ module.exports = {
setupFiles: ['./test/integration/helpers.cjs'], setupFiles: ['./test/integration/helpers.cjs'],
testPathIgnorePatterns: ['/node_modules/', 'test/unit'], testPathIgnorePatterns: ['/node_modules/', 'test/unit'],
testTimeout: 5000, testTimeout: 5000,
globals: {
testServerUrl: 'http://localhost:3005/'
}
}; };

20
node
View File

@ -1,13 +1,15 @@
#!/usr/bin/env bash #!/usr/bin/env bash
user_id=$(id -u) #user_id=$(id -u)
image=btroops #image=btroops
if [[ $1 == run && $2 == test* ]] #if [[ $1 == run && $2 == test* ]]
then #then
port=3005 # port=3005
else #else
port=8080 # port=8080
fi #fi
docker run --rm --init -it -v $PWD:/usr/src/app -u $user_id:$user_id -p $port:$port $image node $@ #docker run --rm --init -it -v $PWD:/usr/src/app -u $user_id:$user_id -p $port:$port $image node $@
source ./scripts/docker-run node $@

20
npm
View File

@ -1,13 +1,15 @@
#!/usr/bin/env bash #!/usr/bin/env bash
user_id=$(id -u) #user_id=$(id -u)
image=btroops #image=btroops
if [[ $1 == run && $2 == test* ]] #if [[ $1 == run && $2 == test* ]]
then #then
port=3005 # port=3005
else #else
port=8080 # port=8080
fi #fi
docker run --rm --init -it -v $PWD:/usr/src/app -u $user_id:$user_id -p $port:$port $image npm $@ #docker run --rm --init -it -v $PWD:/usr/src/app -u $user_id:$user_id -p $port:$port $image npm $@
source ./scripts/docker-run npm $@

View File

@ -1,3 +0,0 @@
#!/usr/bin/env bash
docker run --rm --init -it -v $PWD:/usr/src/app -p 8080:8080 btroops bash

View File

@ -1,3 +0,0 @@
#!/usr/bin/env bash
docker run --rm --init -it --hostname btroops-test -v $PWD:/usr/src/app -p 8080:8080 --name btroops-test btroops bash

13
scripts/docker-run Executable file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env bash
user_id=$(id -u)
image=btroops
if [[ $2 == run && $3 == test* ]]
then
port=3005
else
port=8080
fi
docker run --rm --init -it -v $PWD:/usr/src/app -u $user_id:$user_id -p $port:$port $image $@

View File

@ -1,5 +1,24 @@
const { createServer } = require('esbuild-server'); const { createServer } = require('esbuild-server');
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs');
const { IncomingMessage } = require('node:http');
class Request extends IncomingMessage {
constructor(socket) {
super(socket);
}
get url() {
console.log('getter called', this._url);
return this._url;
}
set url(val) {
console.log('setter called', val);
this._url = val;
}
}
const resolveImportedSvg = { const resolveImportedSvg = {
name: 'resolveImportedSvg', name: 'resolveImportedSvg',
@ -12,21 +31,36 @@ const resolveImportedSvg = {
} }
} }
const resolveSvgImports = {
name: 'resolveSvgImports',
setup(build) {
build.onStart(() => {
fs.rmSync(path.resolve(build.initialOptions.outdir), { recursive: true, force: true });
});
build.onResolve({ filter: /\.svg$/ }, args => {
return {
path: path.resolve('public', args.path),
};
});
}
}
const server = createServer( const server = createServer(
{ {
bundle: true, bundle: true,
define: { define: {
'env': `"${process.env.NODE_ENV || 'dev'}"`, 'env': `"${process.env.NODE_ENV || 'dev'}"`,
}, },
entryPoints: ['src/*.js'], entryPoints: ['src/index.js', 'src/soldier_record_block.js', 'src/map.js'],
...(process.env.NODE_ENV !== 'test') && { outdir: 'build',
outdir: 'build' // ...(process.env.NODE_ENV !== 'test') && {
}, // outdir: 'build'
plugins: [resolveImportedSvg], // },
plugins: [resolveSvgImports],
loader: { loader: {
'.svg': 'file' '.svg': 'file'
}, },
metafile: true,
assetNames: 'assets/images/[name]-[hash]', assetNames: 'assets/images/[name]-[hash]',
}, },
{ {
@ -34,7 +68,8 @@ const server = createServer(
...(process.env.NODE_ENV === 'test') && { ...(process.env.NODE_ENV === 'test') && {
port: 3005, port: 3005,
injectLiveReload: false, injectLiveReload: false,
watch: false watch: false,
// http: { IncomingMessage: Request }
} }
} }
); );

View File

@ -80,11 +80,20 @@ function loadScenario(data) {
async function buildScenario(req) { async function buildScenario(req) {
console.log('req', req); console.log('req', req);
const svg = scenarioTemplate.querySelector('svg').cloneNode(true); console.log('fresh template', scenarioTemplate.querySelector('svg'));
document.querySelector('object').contentDocument.querySelector('svg').replaceWith(svg);
const svg = scenarioTemplate.querySelector('svg').cloneNode(true);
// console.log('document', document.querySelector('object').contentDocument);
document.querySelector('object').contentDocument.querySelector('svg').remove();
document.querySelector('object').contentDocument.append(svg);
gameboard.stop();
recordSheet.stop();
const startLocs = svg.querySelector('.start-locations');
const scenario = await req; const scenario = await req;
const startLocs = scenario.querySelector('.start-locations');
console.log(scenario); console.log(scenario);
@ -119,17 +128,15 @@ async function buildScenario(req) {
}); });
const refsQuery = [...refs[filename]].join(', '); const refsQuery = [...refs[filename]].join(', ');
external.querySelectorAll(refsQuery).forEach(node => defs.append(node)); external.querySelectorAll(refsQuery).forEach(node => defs.append(svg.ownerDocument.importNode(node, true)));
}); });
}); });
scenario.querySelectorAll('use.mapsheet').forEach(el => gb.prepend(el)); scenario.querySelectorAll('use.mapsheet').forEach(el => gb.prepend(svg.ownerDocument.importNode(el, true)));
grid.before(scenario.querySelector('.start-locations')); if (startLocs) grid.before(svg.ownerDocument.importNode(startLocs, true));
const scenarioGrid = scenario.querySelector('.grid'); const scenarioGrid = scenario.querySelector('.grid');
console.log('scenarioGrid', scenarioGrid);
if (scenarioGrid) { if (scenarioGrid) {
grid.replaceWith(svg.ownerDocument.importNode(scenarioGrid, true)); grid.replaceWith(svg.ownerDocument.importNode(scenarioGrid, true));
} }

View File

@ -175,6 +175,7 @@ function selectOffBoard() {
} }
function select(data) { function select(data) {
console.log('select', data);
const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data)); const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data));
const isSelected = counter?.classList.contains(soldier.getSelectedClass()); const isSelected = counter?.classList.contains(soldier.getSelectedClass());
@ -204,6 +205,8 @@ export function start(el) {
startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard)); startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard));
getCells(svg).forEach(cell => { getCells(svg).forEach(cell => {
if (cell.dataset.x === '0' && cell.parentElement.dataset.y === '0') console.log('cell', cell);
cell.addEventListener('click', e => { cell.addEventListener('click', e => {
const occupant = getCellOccupant(cell); const occupant = getCellOccupant(cell);
let toPlace = placing.pop(); let toPlace = placing.pop();
@ -300,6 +303,11 @@ export function start(el) {
console.log('gameboard.js loaded'); console.log('gameboard.js loaded');
} }
export function stop() {
Observable.unsubscribe('select', select);
Observable.unsubscribe('endmove', endMove);
}
export function getUnits() { export function getUnits() {
return soldier.getAllCounters(svg); return soldier.getAllCounters(svg);
} }

View File

@ -195,3 +195,8 @@ export function start(startLoc, units) {
Observable.subscribe('select', select); Observable.subscribe('select', select);
Observable.subscribe('endmove', endMove); Observable.subscribe('endmove', endMove);
} }
export function stop() {
Observable.unsubscribe('select', select);
Observable.unsubscribe('endmove', endMove);
}

View File

@ -9,3 +9,8 @@ global.takeScreenshot = async (driver) => {
await mkdir(dir, { recursive: true }); await mkdir(dir, { recursive: true });
await writeFile(`${dir}/${fileName.replaceAll('/', '-')}`, image, 'base64'); await writeFile(`${dir}/${fileName.replaceAll('/', '-')}`, image, 'base64');
}; };
global.url = (relativeOrAbsolute) => {
const location = new URL(relativeOrAbsolute, global.testServerUrl);
return location.href;
}

View File

@ -1,7 +1,6 @@
const { Builder } = require('selenium-webdriver'), const { Builder } = require('selenium-webdriver'),
chrome = require('selenium-webdriver/chrome.js'), chrome = require('selenium-webdriver/chrome.js'),
chromeOptions = new chrome.Options(), chromeOptions = new chrome.Options();
{ expect, it } = require('@jest/globals');
chromeOptions.addArguments('--headless', '--disable-gpu', '--no-sandbox'); chromeOptions.addArguments('--headless', '--disable-gpu', '--no-sandbox');
chromeOptions.enableBidi(); chromeOptions.enableBidi();
@ -9,11 +8,12 @@ chromeOptions.enableBidi();
let driver; let driver;
beforeEach(async () => { beforeEach(async () => {
driver = new Builder().forBrowser('chrome').setChromeOptions(chromeOptions).build(); const builder = new Builder().forBrowser('chrome').setChromeOptions(chromeOptions);
driver = builder.build();
}); });
it('loads the page', async () => { it('loads the page', async () => {
await driver.get('http://localhost:3005'); await driver.get(url('/'));
expect(await driver.getTitle()).toEqual('Infantry Combat Solo Basic'); expect(await driver.getTitle()).toEqual('Infantry Combat Solo Basic');
}); });

View File

@ -1,44 +1,49 @@
const { Builder, By, until } = require('selenium-webdriver'), const { Builder, By, until } = require('selenium-webdriver'),
chrome = require('selenium-webdriver/chrome.js'), chrome = require('selenium-webdriver/chrome.js'),
chromeOptions = new chrome.Options(), chromeOptions = new chrome.Options(),
{ expect, it } = require('@jest/globals'), { readFile, readdir } = require('node:fs/promises'),
{ readFile } = require('node:fs/promises'),
{ HttpResponse } = require('selenium-webdriver/devtools/networkinterceptor'); { HttpResponse } = require('selenium-webdriver/devtools/networkinterceptor');
chromeOptions.addArguments('--headless', '--disable-gpu', '--no-sandbox'); chromeOptions.addArguments('--headless', '--disable-gpu', '--no-sandbox');
chromeOptions.enableBidi();
let driver; const buildPath = 'build/assets/images';
const defaultScenario = 'scenario-side_show';
const fixtureFilePath = './test/integration/fixtures/scenario-test.svg';
const selected = expect.stringContaining('selected');
const notSelected = expect.not.stringContaining('selected');
let driver, httpResponse;
beforeAll(async () => {
const filenames = await readdir(buildPath);
const scenario = filenames.find(filename => filename.includes(defaultScenario));
httpResponse = new HttpResponse(url(`/assets/images/${scenario}`));
httpResponse.body = await readFile(fixtureFilePath, 'utf8');
httpResponse.addHeaders('Content-Type', 'image/svg+xml');
});
beforeEach(async () => { beforeEach(async () => {
driver = new Builder().forBrowser('chrome').setChromeOptions(chromeOptions).build(); driver = new Builder().forBrowser('chrome').setChromeOptions(chromeOptions).build();
const connection = await driver.createCDPConnection('page')
await driver.onIntercept(connection, httpResponse, async () => {});
await driver.get(url('/'));
const mapPlaceholderEl = await driver.findElement(By.css('.map-placeholder'));
await driver.wait(until.elementIsNotVisible(mapPlaceholderEl), 1000);
}); });
it('selects and deselects a trooper by clicking on its counter', async () => { it('selects and deselects a trooper by clicking on its counter', async () => {
const connection = await driver.createCDPConnection('page')
const url = 'http://localhost:3005/assets/images/scenario-side_show.svg';
const httpResponse = new HttpResponse(url);
httpResponse.body = await readFile('./test/integration/fixtures/scenario-test.svg', 'utf8');
httpResponse.addHeaders('Content-Type', 'image/svg+xml');
await driver.onIntercept(connection, httpResponse, async () => {});
await driver.get('http://localhost:3005');
await driver.wait(until.elementLocated(By.css('#dice')), 1000);
const record = await driver.findElement(By.css('.soldier-record')); const record = await driver.findElement(By.css('.soldier-record'));
const notSelected = expect.not.stringContaining('selected'); const objectEl = await driver.findElement(By.css('object'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]';
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
const objectEl = await driver.findElement(By.css('object'));
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
const svg = await driver.findElement(By.css('svg'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]', const counter = await driver.findElement(By.css(selector), svg);
svg = await driver.findElement(By.css('svg')),
counter = await driver.findElement(By.css(selector), svg),
selected = expect.stringContaining('selected');
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
await counter.click(); await counter.click();
expect(await counter.getAttribute('class')).toEqual(selected); expect(await counter.getAttribute('class')).toEqual(selected);
@ -54,37 +59,20 @@ it('selects and deselects a trooper by clicking on its counter', async () => {
}); });
it('selects and deselects trooper by clicking on its record', async () => { it('selects and deselects trooper by clicking on its record', async () => {
const connection = await driver.createCDPConnection('page')
const url = 'http://localhost:3005/assets/images/scenario-side_show.svg';
const httpResponse = new HttpResponse(url);
httpResponse.body = await readFile('./test/integration/fixtures/scenario-test.svg', 'utf8');
httpResponse.addHeaders('Content-Type', 'image/svg+xml');
await driver.onIntercept(connection, httpResponse, async () => {});
await driver.get('http://localhost:3005');
await driver.wait(until.elementLocated(By.css('#dice')), 1000);
const record = await driver.findElement(By.css('.soldier-record')); const record = await driver.findElement(By.css('.soldier-record'));
const notSelected = expect.not.stringContaining('selected'); const objectEl = await driver.findElement(By.css('object'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]';
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
const objectEl = await driver.findElement(By.css('object'));
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
const svg = await driver.findElement(By.css('svg'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]', const counter = await driver.findElement(By.css(selector), svg);
svg = await driver.findElement(By.css('svg')),
counter = await driver.findElement(By.css(selector), svg);
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
await driver.switchTo().defaultContent(); await driver.switchTo().defaultContent();
await record.click(); await record.click();
const selected = expect.stringContaining('selected');
expect(await record.getAttribute('class')).toEqual(selected); expect(await record.getAttribute('class')).toEqual(selected);
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
expect(await counter.getAttribute('class')).toEqual(selected); expect(await counter.getAttribute('class')).toEqual(selected);
@ -92,36 +80,21 @@ it('selects and deselects trooper by clicking on its record', async () => {
await record.click(); await record.click();
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
}); });
it('selects a trooper by clicking on its counter and deselects it by clicking on its record', async () => { it('selects a trooper by clicking on its counter and deselects it by clicking on its record', async () => {
const connection = await driver.createCDPConnection('page')
const url = 'http://localhost:3005/assets/images/scenario-side_show.svg';
const httpResponse = new HttpResponse(url);
httpResponse.body = await readFile('./test/integration/fixtures/scenario-test.svg', 'utf8');
httpResponse.addHeaders('Content-Type', 'image/svg+xml');
await driver.onIntercept(connection, httpResponse, async () => {});
await driver.get('http://localhost:3005');
await driver.wait(until.elementLocated(By.css('#dice')), 1000);
const record = await driver.findElement(By.css('.soldier-record')); const record = await driver.findElement(By.css('.soldier-record'));
const notSelected = expect.not.stringContaining('selected'); const objectEl = await driver.findElement(By.css('object'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]';
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
const objectEl = await driver.findElement(By.css('object'));
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
const svg = await driver.findElement(By.css('svg'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]', const counter = await driver.findElement(By.css(selector), svg);
svg = await driver.findElement(By.css('svg')),
counter = await driver.findElement(By.css(selector), svg),
selected = expect.stringContaining('selected');
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
await counter.click(); await counter.click();
expect(await counter.getAttribute('class')).toEqual(selected); expect(await counter.getAttribute('class')).toEqual(selected);
@ -131,43 +104,25 @@ it('selects a trooper by clicking on its counter and deselects it by clicking on
await record.click(); await record.click();
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
}); });
it('selects a trooper by clicking on its record and deselects it by clicking on its counter', async () => { it('selects a trooper by clicking on its record and deselects it by clicking on its counter', async () => {
const connection = await driver.createCDPConnection('page')
const url = 'http://localhost:3005/assets/images/scenario-side_show.svg';
const httpResponse = new HttpResponse(url);
httpResponse.body = await readFile('./test/integration/fixtures/scenario-test.svg', 'utf8');
httpResponse.addHeaders('Content-Type', 'image/svg+xml');
await driver.onIntercept(connection, httpResponse, async () => {});
await driver.get('http://localhost:3005');
await driver.wait(until.elementLocated(By.css('#dice')), 1000);
const record = await driver.findElement(By.css('.soldier-record')); const record = await driver.findElement(By.css('.soldier-record'));
const notSelected = expect.not.stringContaining('selected'); const objectEl = await driver.findElement(By.css('object'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]';
expect(await record.getAttribute('class')).toEqual(notSelected); expect(await record.getAttribute('class')).toEqual(notSelected);
const objectEl = await driver.findElement(By.css('object'));
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
const svg = await driver.findElement(By.css('svg'));
const selector = '.counter[data-allegiance="attacker"][data-number="1"]', const counter = await driver.findElement(By.css(selector), svg);
svg = await driver.findElement(By.css('svg')),
counter = await driver.findElement(By.css(selector), svg);
expect(await counter.getAttribute('class')).toEqual(notSelected); expect(await counter.getAttribute('class')).toEqual(notSelected);
await driver.switchTo().defaultContent(); await driver.switchTo().defaultContent();
await record.click(); await record.click();
const selected = expect.stringContaining('selected');
expect(await record.getAttribute('class')).toEqual(selected); expect(await record.getAttribute('class')).toEqual(selected);
await driver.switchTo().frame(objectEl); await driver.switchTo().frame(objectEl);
expect(await counter.getAttribute('class')).toEqual(selected); expect(await counter.getAttribute('class')).toEqual(selected);

View File

@ -1,7 +1,7 @@
console.log('\nSpawning server process...'); console.log('\nSpawning server process...');
const { spawn } = require('child_process'); const { spawn } = require('child_process');
module.exports = async function () { module.exports = async function (globalConfig, projectConfig) {
const child = spawn('node', ['server.cjs']); const child = spawn('node', ['server.cjs']);
child.stdout.on('data', (data) => { child.stdout.on('data', (data) => {
@ -13,7 +13,7 @@ module.exports = async function () {
child.stderr.on('data', (data) => { child.stderr.on('data', (data) => {
const str = data.toString(); const str = data.toString();
console.log('[server]', str); console.log('[server]', str);
if (str.includes('localhost:3005')) { if (str.includes(projectConfig.globals.testServerUrl)) {
setTimeout(resolve, 200); setTimeout(resolve, 200);
} }
}); });