【问题标题】:Mocking a function that is called during file load in Jest在 Jest 中模拟文件加载期间调用的函数
【发布时间】:2020-03-05 00:48:31
【问题描述】:

我有一个我正在尝试进行单元测试的文件。我希望通过调用feathersauth 库方法以及测试导出的loginlogout 方法调用适当的库方法来测试API 对象是否被创建。

我想模拟对库方法的所有调用,以便对这个文件进行单元测试。

这是我目前所拥有的:

api.js

import feathers from '@feathersjs/feathers'
import auth from '@feathersjs/authentication-client'

export const DEFAULT_TIMEOUT = 30

const api = feathers()
api.configure(auth({ storage: window.localStorage, timeout: DEFAULT_TIMEOUT * 1000 }))

const login = async (credentials) => {
  return api.authenticate(credentials)
}

const logout = async () => {
  return api.logout()
}

export default { login, logout }

api.test.js

import feathers from '@feathersjs/feathers'
import auth from '@feathersjs/authentication-client'

import api, { DEFAULT_TIMEOUT } from './api'

const mockFeathers = {
  configure: jest.fn(),
  authenticate: jest.fn(),
  logout: jest.fn()
}
jest.mock('@feathersjs/feathers', () => jest.fn(() => mockFeathers))
jest.mock('@feathersjs/authentication-client', () => jest.fn(() => 'AUTH'))

describe('helpers/api', () => {
  it('creates a Feathers app with authentication', () => {
    expect(feathers).toHaveBeenCalled()
    expect(auth).toHaveBeenCalledWith({
      storage: window.localStorage,
      timeout: DEFAULT_TIMEOUT * 1000
    })

    expect(mockFeathers.configure).toHaveBeenCalledWith('AUTH')
  })

  describe('login', () => {
    it('authenticates with the Feathers app', async () => {
      const loginResult = { loggedIn: true }
      mockFeathers.authenticate.mockImplementationOnce(() => loginResult)

      const credentials = { email: 'user@example.com', password: 'password' }
      const result = await api.login(credentials)

      expect(mockFeathers.authenticate).toHaveBeenCalledWith(credentials)
      expect(result).toEqual(loginResult)
    })
  })

  describe('logout', () => {
    it('logs out from the Feathers app', async () => {
      await api.logout()

      expect(mockFeathers.logout).toHaveBeenCalled()
    })
  })
})

这会因ReferenceError: mockFeathers is not defined 而失败,因为似乎在定义mockFeathers 之前正在加载api.js(因此调用了feathers 方法)。我尝试将import api 行移到mockFeathers 定义的下方,但这并没有什么不同。

如何在加载api.js 文件之前模拟feathers() 调用的结果?

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    我确实设法通过完全删除导入并在beforeAll 块中api.js 中的api.js 来实现这一点。这可行,但对我来说似乎有点混乱,如果您从 required 文件有多个单独的导入,则无法很好地扩展。

    api.test.js

    // Remove the import line.
    //import api, { DEFAULT_TIMEOUT } from './api'
    
    describe('helpers/api', () => {
      let api, DEFAULT_TIMEOUT
      beforeAll(() => {
        // Require the file here so that the mock has time to be defined.
        ;({ default: api, DEFAULT_TIMEOUT } = require('./api'))
      })
    
      // ...
    })
    

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多