简体   繁体   English

jest.fn() 的别名?

[英]Aliases for jest.fn()?

I have two different libraries that I'm using to make mocks in Jest.我有两个不同的库用于在 Jest 中进行模拟。 The libraries have the same function called get .这些库具有相同的名为get函数。 This is a problem for my current implementation since get is used by two different libraries is it possible to use an alias for mock functions (jest.fn()) or maybe some kind of workaround that doesn't ruin the integrity of the current implementation?这是我当前实现的一个问题,因为get被两个不同的库使用,是否可以使用模拟函数的别名(jest.fn())或者某种不会破坏当前实现完整性的解决方法?

Here is my current implementation and I would I like to keep this way if possible:这是我目前的实现,如果可能的话,我想保持这种方式:

let get: jest.Mock<{}>
jest.mock('rxjs/ajax', () => {
  get = jest.fn()
  return { ajax: { get } }
})

let get as cookieGet: jest.Mock<()> // Can I do something like this 
jest.mock('js-cookie', () => {
  get = jest.fn()
  return { get }
})

I'm not too familiar with aliases in JS or they Jest handles things like this so any help is much appreciated.我不太熟悉 JS 中的别名,或者他们 Jest 处理这样的事情,所以非常感谢任何帮助。

It's unnecessary to use { get } shorthand property syntax for object literal if it results in name collisions.如果会导致名称冲突,则没有必要对对象字面量使用{ get }速记属性语法。

Another problem is that a variable needs to have mock prefix in order to be used in the scope of jest.mock factory function.另一个问题是变量需要有mock前缀才能在jest.mock工厂函数的范围内使用。 As the documentation states,正如文档所述,

A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. factory 参数的一个限制是,因为对 jest.mock() 的调用被提升到文件的顶部,所以不可能先定义一个变量然后在工厂中使用它。 An exception is made for variables that start with the word 'mock'.以单词“mock”开头的变量是一个例外。 It's up to you to guarantee that they will be initialized on time!由您来保证它们会按时初始化!

It can be:有可能:

import ... from 'rxjs/ajax';
import ... from 'js-cookie';

let mockRxAjaxGet: jest.Mock<{}>

jest.mock('rxjs/ajax', () => {
  mockRxAjaxGet = jest.fn()
  return { ajax: { get: mockRxAjaxGet } }
})

let mockJsCookieGet: jest.Mock<()>
jest.mock('js-cookie', () => {
  mockJsCookieGet = jest.fn()
  return { get: mockJsCookieGet }
})

The problem is that once jest.mock is hoisted above imports, it will be evaluated when let variables are in temporal dead zone and cannot be assigned.问题是,一旦jest.mock被提升到导入之上,当let变量处于时间死区并且无法分配时,它将被评估。

So let should be preferably changed to var , which is hoisted.所以let最好改成var ,它被提升了。 Or mocked function be imported as usual and used with get as jest.Mock<...> where a spy is expected.或者像往常一样导入get as jest.Mock<...>函数,并在需要间谍的地方与get as jest.Mock<...>使用。 mocked helper can be used to enforce TypeScript type safety. mocked助手可用于强制执行 TypeScript 类型安全。

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

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