开玩笑的测试用例在beforeAll()块之前执行

时间:2020-06-01 06:12:49

标签: javascript node.js typescript jestjs

我有一个测试用例模块,它在单独的模块上执行,当试图运行测试用例文件(即sample.test.ts)时,测试用例与beforeAll块并行执行,这导致测试用例失败。由于这种并行执行,测试用例模块中的值被分配为undefined而不是原始值。该如何解决?
sample.test.ts

import { TestCase } from '../path/to/TestCase class';
import { TestHelper } from '../path/to/TestHelper class';
const testCase = new TestCase();
const testHelper = new TestCase();
  // Test suite for GET request - Search by ID
  describe('GET Request - Search by id', () => {
    let searchId: string;
    // Preparing Test Suite
    beforeAll(async () => {
      const response = await testHelper.register('url); // performing db operation - register using supertest
      searchId = response.body._id; // getting registered documment id in response
    }, 20000);
    // Executing
    testCase.validateResponseCode(searchId); // Performing Get request - search by id
  });

test_cases.ts

export class TestCase<T> {
  validateResponseCode(id: string): void {
    console.log(id); // undefined is assigned to id instead of assigning objectId which is passed in test module
    it('sample test case', async () => {
      // implementation
    }, 20000);
  }

}

1 个答案:

答案 0 :(得分:0)

我认为beforeAll应该在describe函数之外。

还要在searchId之外定义beforeAll变量:

  let searchId: string;

  // Preparing Test Suite
  beforeAll(async () => {
    const response = await testHelper.register('url); // performing db operation - register using supertest
    searchId = response.body._id; // getting registered documment id in response
  });

  describe('GET Request - Search by id', () => {
    // Executing
    testCase.validateResponseCode(searchId); // Performing Get request - search by id
  });