gpt4 book ai didi

typescript - 如何模拟和扩展外部定义的类及其原型(prototype)?

转载 作者:行者123 更新时间:2023-12-02 02:42:24 25 4
gpt4 key购买 nike

背景故事

我正在玩一款名为 screeps 的游戏该游戏允许您编写一个在游戏中执行操作的机器人/人工智能。实现此目的的方法是上传在具有可用常量、类和定义的环境中运行的代码。

这些定义是用以下包定义的 https://www.npmjs.com/package/@types/screeps

现在我正在 typescript 中编写代码并使用汇总来编译它以进行爬行,我正在使用以下入门包 https://github.com/screepers/screeps-typescript-starter

我正在尝试使用以下框架进行模拟 https://www.npmjs.com/package/@fluffy-spoon/substitute

问题

在 Mocha 中运行时,我必须从游戏中 stub /模拟环境的功能,在测试框架中运行时它不存在。我成功地模拟了这些常量,并在其他人的帮助下让它们在 Mocha 中运行。但现在我坚持扩展对象的原型(prototype) Creep

原型(prototype).ts

Object.defineProperty(Creep.prototype, "task", {
get() {
... logic
},
set(task: ITask | null) {
... logic
}
})

测试

import "../constants"
import "../../src/tasks/prototypes"
import { Task } from "tasks/Task"
import { Game, Memory } from "./mock"
import { assert } from "chai"
import { Substitute, Arg } from "@fluffy-spoon/substitute"

describe("tasks", () => {
before(() => {
// runs before all test in this block
})

beforeEach(() => {
// runs before each test in this block
// @ts-ignore : allow adding Game to global
global.Game = _.clone(Game) as Game
// @ts-ignore : allow adding Memory to global
global.Memory = _.clone(Memory)
})

it("Creep should have extended prototyped", () => {
const testCreep = Substitute.for<Creep>()

const task = testCreep.task

assert.isNotNull(task)

})
})

当我运行测试时,出现以下错误

...\dist\test-unit.bundle.js:3324
}(chai));
^
ReferenceError: Creep is not defined

这是有道理的,因为 Creep 类尚未由游戏引擎或测试环境定义,因此导入prototypes.ts 无法扩展它但我不确定如何真正使其发挥作用。

最佳答案

我设法通过按照常量定义中的方式运行它

模拟.ts

import { Substitute, Arg } from "@fluffy-spoon/substitute"

export const Game = Substitute.for<Game>()

const mockScreeps = () => {
const g = global as any

g.Game = Game
g.Creep = (function() {
function Creep() {}

return Creep
})()

g.RoomObject = (function() {
function RoomObject() {}

return RoomObject
})()

g.RoomPosition = (function() {
function RoomObject() {}

return RoomObject
})()
}

mockScreeps()

测试

import "../constants"
import { Memory } from "./mock"
import { assert } from "chai"
import "../../src/tasks/prototypes"

describe("tasks", () => {
before(() => {
// runs before all test in this block
})

beforeEach(() => {
// runs before each test in this block
// @ts-ignore : allow adding Memory to global
global.Memory = _.clone(Memory)
})

it("Creep should have extended prototyped", () => {
const creep = new Creep("test")
creep.memory = {
task: {
tick: 123,
name: "dummy"
}
}

const task = creep.task
assert.isNotNull(task)
if (task && creep.memory.task) {
assert.isString(task.memory.name)
assert.equal(task.memory.name, creep.memory.task.name)
}

})
})

它现在运行我的测试,我只需要在使用尚未模拟的东西进行测试时扩展模拟。

关于typescript - 如何模拟和扩展外部定义的类及其原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56951113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com