如何将构造函数与导入的ES6模块固执?
我想在测试文件中存根类的构造函数。说我有以下内容:
// 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用.mjs,您基本上希望将代码重新处理为各地的依赖性注射。和双脂箭的功能:P
with .mjs you basically want to re-work your code to dependency injections everywhere. and functions to double fat arrows :P