我希望能够测试在单元测试中实例化的机器人,该单元测试导入从另一个文件Controller.ts实例化的Grid。
问题是创建该网格的控制器端点可以正常工作,因为它将创建一个Grid实例并导出它,以便Robot类可以在以后使用它。但这不是单元测试中的情况。
这是代码:
Robot.ts
import { grid } from "./controller";
class Robot {
constructor(public x, public y, public orientation) {}
move(){
if (grid.isOffGrid(x, y)) {
}
}
}
Controller.ts
export let grid = null;
router.post("/", bodyParser, (req, res, next) => {
// some code
grid = new Grid(5, 4);
}
Robot.test.ts
import Robot from "./Robot";
describe("Robot", () => {
it("should position robot on grid", () => {
const x = 0;
const y = 1;
const orientation = "N";
const robot = new Robot(x, y, orientation);
})
})
当我尝试运行npm test
时,收到以下消息:
Cannot read property 'isOffGrid' of undefined
if (grid.isOffGrid(x, y)) {
// more code
}
如何将在测试中实例化的网格导入Robot.ts中,而不是从Controller.ts中导入{grid}?还有另一种方法吗?