开玩笑地将变量传递给测试

强尼

我有各种测试套件所需的变量。我决定不使用每个套件进行初始化,而是决定使用一个测试文件,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烧瓶)

如果我仅在导入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如何组织不同的流程?而且是的,我可以将参数放在全局名称空间中,但我想避免这样做。

强尼

我找到了解决方案。没有传递foofoobar函数,而是将导出,然后在需要的地方导入。

因此,我的测试文件如下所示(带有export 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章