当我尝试使用从数据库获取的参数执行 JEST 测试时,它根本不起作用...我尝试了一个没有数据库的示例,但它的工作方式不同。
查看代码
// Example function that queries IDs from the database
async function fetchIDsFromDatabase() {
// Simulating an asynchronous database query
return [1, 2, 3]; // Example list of IDs returned by the database
}
// Test using Jest
describe('Test for IDs returned from the database', () => {
let ids;
// Before all tests, fetch IDs from the database
beforeAll(async () => {
ids = await fetchIDsFromDatabase();
});
// Test to verify if the list of IDs is not empty
test('Checks if the list of IDs is not empty', () => {
expect(ids).toBeTruthy();
});
// Iterate over each ID returned from the database using test.each
test.each(ids)('Testing ID %i', async (id) => {
// Here you can perform test operations for each ID
expect(id).toBeGreaterThan(0); // Simple assertion example
// Add more assertions as needed
});
});
退货是
测试从数据库返回的ID
√ 检查 ID 列表是否不为空(2 毫秒)
× 测试 ID %i(1 毫秒)
● 测试从数据库返回的 ID › 测试 ID %i
`.each` must be called with an Array or Tagged Template Literal.
Instead was called with: undefined
20 |
21 | // Iterate over each ID returned from the database using test.each
> 22 | test.each(ids)('Testing ID %i', async (id) => {
| ^
23 | // Here you can perform test operations for each ID
24 | expect(id).toBeGreaterThan(0); // Simple assertion example
25 | // Add more assertions as needed
at each (__TEST__/api.test.js:22:10)
at Object.describe (__TEST__/api.test.js:8:3)
测试套件:1 次失败,总共 1 次
测试:1 次失败,1 次通过,总共 2 次
快照: 共 0 个
时间:0.508 秒,预计 1 秒
运行所有测试套件。
问题不在于笑话,问题在于代码。
这是正确的代码:
let ids = [];
beforeAll(async () => {
ids = await fetchIDsFromDatabase();
});
test('Checks if the list of IDs is not empty', () => {
expect(ids).toBeTruthy();
expect(ids.length).toBeGreaterThan(0); // Ensure the array is not empty
});
describe('Dynamic ID tests', () => {
ids.forEach(id => {
test(`Testing ID ${id}`, async () => {
expect(id).toBeGreaterThan(0); // Simple assertion example
// Add more assertions as needed
});
});
});
ids
已正确初始化并确定范围。ids
不为空。test.each
在填充ID之前尝试访问ID的问题。