简体   繁体   English

如何从导入的 ES6 模块中存根构造函数?

[英]How to stub a constructor from an imported ES6 module?

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.是否有一些神奇的Object.setPrototypeOf()Foo.prototype = ReplacedFoo之类的调用,我可以确保functionThatUsesFoo()使用我的存根构造函数。 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.我发现的关于这个主题的大多数资源都在使用 nodejs require()和一个在内部使用 node:vm 的测试库。 But I'm using Deno/browser environments where this is not easily available.但我正在使用不易获得的 Deno/浏览器环境。

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.同样,使用导入映射来解决这个问题也不是一个真正令人满意的解决方案,因为它不能很好地扩展,我还不如在那时使用该库。

with .mjs you basically want to re-work your code to dependency injections everywhere.使用 .mjs,您基本上想重新编写代码以在任何地方进行依赖注入。 and functions to double fat arrows :P和双胖箭头的功能:P

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM