【发布时间】:2020-03-05 00:48:31
【问题描述】:
我有一个我正在尝试进行单元测试的文件。我希望通过调用feathers 和auth 库方法以及测试导出的login 和logout 方法调用适当的库方法来测试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