【发布时间】:2021-09-16 06:14:09
【问题描述】:
我正在用 JS 为战舰游戏构建一个游戏板,它的当前结构如下:
export default class Gameboard {
constructor(size) {
this.grid = this.#createMatrix(size);
}
#createMatrix(size) {
const mat = new Array(size);
for (let i = 0; i < size; i++) {
// ship - for ship object if it exists, attacked - isAttacked?,
// index - relative placement of ship tile wrt whole ship, if it exists
mat[i] = new Array(size).fill({ ship: null, attacked: false, index: -1 });
}
return mat;
}
/**
* @param {Ship} ship to be placed
* @param {int} x starting x coordinate of ship placement
* @param {int} y starting y coordinate of ship placement
*/
placeShip(ship, x, y) {
for (let i = 0; i < ship.length; i++) {
this.grid[x][y]["ship"] = ship;
this.grid[x][y]["index"] = i;
console.log(this.grid[x][y]);
y++; //move to next column for next tile placement
}
}
}
我不明白为什么以下将船水平放置在上面的测试会失败:
it("places ships", () => {
const gameboard = new Gameboard(2);
const ship = new Ship(2);
gameboard.placeShip(ship, 0, 0);
expect(gameboard.grid).toEqual([
[
{ ship: ship, index: 0, attacked: false },
{ ship: ship, index: 1, attacked: false },
],
[defaultObj, defaultObj],
]);
});
错误信息:
似乎在循环时,两列的对象都会更新,但我只想更新一列。
【问题讨论】:
标签: javascript unit-testing testing jestjs tdd