如何将构造函数与导入的ES6模块固执?

发布于 2025-01-29 05:23:01 字数 1290 浏览 3 评论 0原文

我想在测试文件中存根类的构造函数。说我有以下内容:

// Foo.js
export class Foo {}

并且

// myTestFile.js
import {Foo} from "./Foo.js";
import {functionThatUsesFoo} from "./functionThatUsesFoo.js";

class ReplacedFoo {}

// do something to replace `Foo` with `ReplacedFoo` here...

functionThatUsesFoo();

是否有一些魔术object.setPrototypeof()foo.protype = deplacedfoo我可以做的一种调用,以确保function> function> functiontusesfoo ()使用我的固定构造函数。我宁愿不诉诸依赖注入。

我发现有关此主题的大多数资源都使用nodejs require()和一个使用节点:内部使用vm的测试库。但是我正在使用DENO/浏览器环境,在此不容易获得。

我尝试过的某些事情:

  • foo.constructor = depadacedfoo.constructor
  • foo.prototype.constructor = drepacedfoo.prototype.constructor.constructor
  • foo.prototote = reporaceaceFoo.prototype
  • foo.protype =更换
  • object.setPrototypeof(foo,depreacedfoo.prototype)

i Made 解决此类情况,使您可以替换导入文件的内容。但是它有一些不可避免的限制,因此我想在可能的情况下避免使用它。同样,使用导入地图解决这并不是一个令人满意的解决方案,因为它的扩展不佳,我不妨使用库。

I would like to stub the constructor of a class within a test file. Say I have the following:

// Foo.js
export class Foo {}

and

// myTestFile.js
import {Foo} from "./Foo.js";
import {functionThatUsesFoo} from "./functionThatUsesFoo.js";

class ReplacedFoo {}

// do something to replace `Foo` with `ReplacedFoo` here...

functionThatUsesFoo();

Is there some magic Object.setPrototypeOf() or Foo.prototype = ReplacedFoo sort of call that I can do to make sure functionThatUsesFoo() uses my stubbed constructor. I'd prefer not to resort to dependency injection.

Most resources I found about this topic were using nodejs require() and a testing library that uses node:vm internally. But I'm using Deno/browser environments where this is not easily available.

Some things I tried:

  • Foo.constructor = ReplacedFoo.constructor
  • Foo.prototype.constructor = ReplacedFoo.prototype.constructor
  • Foo.prototype = ReplacedFoo.prototype
  • Foo.prototype = ReplacedFoo
  • Object.setPrototypeOf(Foo, ReplacedFoo.prototype)

I made a library to solve situations like these that allows you to replace the contents of imported files. But it has some inevitable limitations so I want to avoid it where possible. Similarly, using import maps to solve this isn't really a satisfying solution either as it doesn't scale well and I might as well use the library at that point.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为你拒绝所有暧昧 2025-02-05 05:23:01

使用.mjs,您基本上希望将代码重新处理为各地的依赖性注射。和双脂箭的功能:P

const makeFunctionThatUsesFoo = (fooInstance) => (funcAgs) => {
 console.log('I feel secure, but stubs stoped working')
}

with .mjs you basically want to re-work your code to dependency injections everywhere. and functions to double fat arrows :P

const makeFunctionThatUsesFoo = (fooInstance) => (funcAgs) => {
 console.log('I feel secure, but stubs stoped working')
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文