[英]Jest passing variables to tests
我有一個各種測試套件需要的變量。 我沒有在每個套件中進行初始化,而是決定使用一個帶有beforeAll
的測試文件來初始化變量並將測試拆分為套件文件,這些文件基本上導出測試。
為了簡單起見,我們假設我的測試文件(唯一的一個jest
調用)是這樣的:
import { foobar } from './foobar'
let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
foobar(foo)
})
我的測試套件文件之一是這樣的:
export const foobar = (foo) => {
it('should be defined', () => expect(foo).toBeDefined())
it('should be bar', () => expect(foo).toMatch('bar'))
}
這是行不通的。 foo
始終undefined
,測試失敗。
foo is bar
✕ should be defined (3 ms)
✕ should be bar
我錯過了什么? 我今天可能會放屁,所以如果我很傻,請原諒。
編輯(@Estus Flask)
如果我只在導入的foobar
文件中定義檢查,如下所示:
export const foobar = (foo) => expect(foo).toBeDefined()
我像這樣修改測試文件:
import { foobar } from './foobar'
let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
it('should be defined', () => foobar(foo))
})
有用:
foo is bar
✓ should be defined (2 ms)
那么,Jest 是如何組織不同流程的呢? 是的,我可以將參數放在全局命名空間中,但我想避免這樣做。
我找到了解決辦法。 我沒有將foo
傳遞給foobar
function,而是導出它然后在需要的地方導入它。
所以,我的測試文件看起來像這樣(導出foo
)
import { foobar } from './foobar'
export let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
foobar()
})
我的測試套件文件如下所示:
import { foo } from './foo.test'
export const foobar = () => {
it('should be defined', () => expect(foo).toBeDefined())
it('should be bar', () => expect(foo).toMatch('bar'))
}
現在一切都過去了:
foo is bar
✓ should be defined (1 ms)
✓ should be bar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.