简体   繁体   中英

Aliases for jest.fn()?

I have two different libraries that I'm using to make mocks in Jest. The libraries have the same function called 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?

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.

It's unnecessary to use { get } shorthand property syntax for object literal if it results in name collisions.

Another problem is that a variable needs to have mock prefix in order to be used in the scope of jest.mock factory function. 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. An exception is made for variables that start with the word '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.

So let should be preferably changed to var , which is hoisted. Or mocked function be imported as usual and used with get as jest.Mock<...> where a spy is expected. mocked helper can be used to enforce TypeScript type safety.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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