【问题标题】:Jest passing variables to tests开玩笑将变量传递给测试
【发布时间】:2021-01-24 14:59:19
【问题描述】:

我有一个变量,各种测试套件都需要它。我决定创建一个带有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 中使用,它应该被定义为一个全局变量。它在其他测试套件中既不能作为本地也不能作为全局访问,因为它们在不同的进程中运行。
  • @EstusFlask 谢谢,检查我对问题的编辑。

标签: node.js jestjs integration-testing


【解决方案1】:

我找到了解决办法。我没有将foo 传递给foobar 函数,而是将其导出然后在需要的地方导入。

所以,我的测试文件看起来像这样(导出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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-05
    • 2021-07-11
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2020-03-25
    相关资源
    最近更新 更多