重用 Jest 单元测试

2024-05-01

我正在尝试使用 Jest 测试几个数据库实现。为了帮助测试这些实现,我首先针对两个实现都预期实现的 API 提出了一组单元测试。

我目前正在努力将这两个实现传递给测试套件。

下面是最简单形式的(虚拟)MongoDB 实现:

class MongoDB {
  async query () {
    console.warn(`This is a dummy function.`)
  }

  async connect () {
    // The real connect takes some time..instead we just simulate it
    await new Promise((resolve, reject) => {
      setTimeout(resolve, 300)
    })
  }
}

这是我的测试的一小段:

let db
beforeAll(async () => {
  db = new MongoDB()
  await db.connect()
  console.log(`mongoDB ready`)
})

async function testDB (db) {
  describe('Basic', async () => {
    test('Valid instance', async () => {
      expect(db).toBeTruthy()
      expect(db.query).toBeTruthy()
    })
  })
}

describe('Tests', async () => {
  console.log(`Running testDB`)
  testDB(db) // Have also unsuccessfully tried changing this to: return testDB(db)
})

我使用这种方法的目标是将所有测试包装在testDB函数并简单地用各种实现来调用它。例如,testDB(new MongoDB()) and testDB(new MemoryDB())等等。

然而,这似乎并没有按预期工作。 上面的代码会产生一个错误,指出:

  ● Tests › Basic › Valid instance

    expect(received).toBeTruthy()

    Expected value to be truthy, instead received
      undefined

的顺序console.log声明似乎表明测试正在运行before db已初始化。

  console.log mongo.test.js:20
    Running testDB

  console.log mongo.test.js:7
    mongoDB ready

整个示例以及结果输出可以是转载于repl.it https://repl.it/@gurupras/testsuite-runs-before-beforeAll.

如何重用单元测试来测试多个实现,而无需重复测试和维护两个版本?


今天面临同样的需求。这是改编自打字稿的方法,但你明白了:

// common/service.test.js
export const commonServiceTests = (name, impl) => {
  describe(`Common tests for ${implName}`, () => {
    // pile your tests here
    test('test1', () => { ... });
    test('test2', () => { ... });
    test('test3', () => { ... });
  });
}

// just to avoid warning, that no tests in test file
describe('Common tests for CommonService implementations', () => {
  test('should be used per implementation', () => {});
});

对于您的每个实施:

// inmemory/service.test.js
import { commonServiceTests } from '../common/service.test';
import ...; // your implementation here

const myInMemoryService = ...; // initialize it

commonServiceTests('InMemory', myInMemoryService);

然后定义的所有测试common/service.test.js将在每个实施测试中执行。

如果你的初始化是async(这是最有可能的),那么你的共享测试应该是async以及。然后:

// common/service.test.js
export const commonServiceTests = (name, impl: Promise) => {
  describe(`Common tests for ${implName}`, () => {
    // pile your async tests here
    test('test1', async () => {
      const svc = await impl;
      return await svc.doSomthingPromisy();
    });
    test('test2', () => { ... });
    test('test3', () => { ... });
  });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重用 Jest 单元测试 的相关文章