首页 > 解决方案 > Nodejs typescript 测试依赖

问题描述

我希望能够测试在单元测试中实例化的机器人,该单元测试导入从另一个文件实例化的网格:Controller.ts。

问题是创建该网格的控制器端点可以工作,因为它将创建一个 Grid 实例并将其导出,以便 Robot 类可以在之后使用它。但在单元测试中并非如此。

这是代码:

机器人.ts

import { grid } from "./controller";

class Robot {
    
    constructor(public x, public y, public orientation) {}

    move(){
        if (grid.isOffGrid(x, y)) {

        }
    }
}

控制器.ts

export let grid = null;

router.post("/", bodyParser, (req, res, next) => {
    // some code

    grid = new Grid(5, 4);

}

机器人测试.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 中导入测试中实例化的 Grid 而不是从 Controller.ts 导入 { grid } ?还有另一种方法吗?

标签: node.jstypescriptexpressjestjs

解决方案


推荐阅读