node.js - 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 } ?还有另一种方法吗?
解决方案
推荐阅读
- azure - 将 GitLab 从 Azure Linux VM 迁移到 AKS
- typescript - 使用 Typescript 和 Lerna 的 Vue 2 组件库的推荐构建配置
- reactjs - 如何使用 Typescript 正确声明 React 包装器组件 (HOC) 的类型
- java - 单例类在多线程环境中保留上一次迭代的值,重置可能会导致 NullPointerException
- ruby-on-rails - 更新 ApplicationRecord 上的 self 属性在生产中不起作用
- java - java.lang.IllegalArgumentException:找不到名为 ... 的缓存,用于 Builder
- java - 调用 getLayoutInflater() 是否需要调用 getActivity()?
- python - (Selenium - Python) 在 webDriver 中查找两个元素之一
- php - php。向数组添加新列,但结果加倍
- pygame - 如何在pygame中偏移矩形