[英]Mocking a function that is called during file load in Jest
我有一個文件,我正在嘗試對其進行單元測試。 我希望通過調用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
,因為它似乎api.js
被加載(以及因此feathers
調用的方法)之前mockFeathers
定義。 我曾嘗試將import api
行mockFeathers
的定義下方,但這並沒有什么區別。
如何在加載api.js
文件之前api.js
feathers()
調用的結果?
我確實通過完全刪除導入並require
在beforeAll
塊中api.js
來實現這一點。 這有效,但對我來說似乎有點混亂,如果您從require
d 文件中有多個單獨的導入,則無法很好地擴展。
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'))
})
// ...
})
似乎是測試失敗的兩個import
語句..請嘗試刪除兩者:
import feathers from '@feathersjs/feathers'
import auth from '@feathersjs/authentication-client'
並保留模擬語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.