首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jest -将测试分离到另一个文件中

jest -将测试分离到另一个文件中
EN

Stack Overflow用户
提问于 2019-12-29 15:32:05
回答 1查看 1.3K关注 0票数 1

是否可以将jest的测试函数分离到另一个文件中,或者它们必须位于执行文件中?

例如:

test_file.js

代码语言:javascript
运行
复制
function tests (input)
{
    it(
        "should pass",
        function ()
        {
            expect(input).toBeTrue()
        }
    )
    // more test functions
}
module.exports = tests

main.js

代码语言:javascript
运行
复制
const tests = require("./test_file.js")

describe(
    "test block 1",
    function ()
    {
        let input

        beforeAll( () => input = true )

        tests(input)
    }
)

现在,input总是没有定义

EN

回答 1

Stack Overflow用户

发布于 2019-12-30 04:51:47

让我们添加一些日志,看看执行这段代码的顺序。

main.test.js

代码语言:javascript
运行
复制
const tests = require('./test_file.js');
console.log('000');
describe('test block 1', function() {
  let input;
  console.log('111');
  beforeAll(() => {
    console.log('222');
    input = true;
  });
  tests(input);
});

test_file.js

代码语言:javascript
运行
复制
console.log('333');
function tests(input) {
  console.log('444');
  it('should pass', function() {
    console.log('555');
    expect(input).toBeTruthy();
  });
}
module.exports = tests;

测试结果:

代码语言:javascript
运行
复制
 FAIL  src/stackoverflow/59520741/main.test.js (9.747s)
  test block 1
    ✕ should pass (7ms)

  ● test block 1 › should pass

    expect(received).toBeTruthy()

    Received: undefined

      4 |   it('should pass', function() {
      5 |     console.log('555');
    > 6 |     expect(input).toBeTruthy();
        |                   ^
      7 |   });
      8 | }
      9 | module.exports = tests;

      at Object.<anonymous> (src/stackoverflow/59520741/test_file.js:6:19)

  console.log src/stackoverflow/59520741/test_file.js:1
    333

  console.log src/stackoverflow/59520741/main.test.js:2
    000

  console.log src/stackoverflow/59520741/main.test.js:5
    111

  console.log src/stackoverflow/59520741/test_file.js:3
    444

  console.log src/stackoverflow/59520741/main.test.js:7
    222

  console.log src/stackoverflow/59520741/test_file.js:5
    555

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        11.015s

现在我们知道了。tests函数将在jest的测试运行程序收集测试用例之前执行。这意味着您的tests函数刚刚声明了测试用例(‘111’和'444‘短语)。此时,beforeAll钩子尚未执行。input变量的值仍然是undefined,并传递给tests函数。

在执行tests函数之后,将声明测试用例。测试运行程序将收集这些测试用例并以正常的方式运行它们。beforeAll钩子将首先执行(‘222’短语)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59520741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档