Javascript Jest在第一次失败后停止执行expect语句
在测试中,我在循环中有以下expect语句,应该执行两次: 预期质量.正文.项目[索引] 但是,在第一次迭代中,如果测试失败,jest不会再次执行循环 如果我将其更改为通过的,jest将在每次循环迭代中执行它: 预期质量.正文.项目[索引] 以下是包含更多上下文的代码:Javascript Jest在第一次失败后停止执行expect语句,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,在测试中,我在循环中有以下expect语句,应该执行两次: 预期质量.正文.项目[索引] 但是,在第一次迭代中,如果测试失败,jest不会再次执行循环 如果我将其更改为通过的,jest将在每次循环迭代中执行它: 预期质量.正文.项目[索引] 以下是包含更多上下文的代码: describe('Recipe', () => { beforeAll(async () => {}); beforeEach(async () => {}); afterEach(a
describe('Recipe', () => {
beforeAll(async () => {});
beforeEach(async () => {});
afterEach(async () => {});
it('should do proper grouping when GET /recipes?filterId=[...]', async () => {
// setup
const res = await request(app.getHttpServer())
.get(...);
expect(res.status).toBe(200);
if (res.body.items) {
[recipeWithProduct1, recipeWithProduct2].forEach((r, index) => {
console.log('LLL200 testing', index);
const nr = { ...r, ...{ updatedAt: '', createdAt: '' } };
delete nr.store;
delete nr.creator;
nr.updatedAt = r.updatedAt.toISOString();
nr.createdAt = r.createdAt.toISOString();
nr.filters = nr.filters.map(f => f.id) as any; // TODO: fix this coersion
// expect(true).toBe(true); // console.log above prints twice if we uncomment this and
// comment the expect below
expect(nr).toEqual(res.body.items[index]); // fails only once
});
}
expect(res.body.total).toEqual(2);
})
});
如何让jest执行所有expect语句,即使前面的语句失败了
我使用的是jest版本23.6.0。这种情况正在发生,因为内部expect正在抛出错误。为了让它们都运行,您可以在不同的测试用例中分离它们 下面是一个示例,说明测试的改进版本是什么样子的:
describe('Recipe', () => {
let res;
beforeAll(async () => {
res = await request(app.getHttpServer())
.get();
});
beforeEach(async () => {});
afterEach(async () => {});
describe('response', () => {
describe.each([
[recipeWithProduct1, 0],
[recipeWithProduct2, 1]
])('receipe %j %#', (receipe, index) => {
it(`should match res.body.items[${index}]`, () => {
expect(res.body.items[index]).toEqual(
expect.objectContaining({
...receipe,
createdAt: receipe.createdAt.toISOString(),
updatedAt: receipe.updatedAt.toISOString(),
})
);
})
})
it('should have status 200', () => {
expect(res).toHaveProperty('status', 200)
})
it('should have body.total', () => {
expect(res).toHaveProperty('body.total', 2);
})
})
});
我想最好的选择是将您的规范分开,这也是在两个单独的it块中编写test-then-expect时要遵循的最佳实践。任何内部expect的证据都会抛出错误?,您可以尝试在try-Catch中包装虚假断言。我遇到了问题,因为recipeWithProduct1是在Beforeach块中创建的。每个块中的配方都没有定义。想法?你可以在上面的范围内定义它,就像我在res中定义的那样,在beforeach中,你可以设置它的值value@Gezim描述和它是在同步上下文中计算的,我已经用指定的数据引用了变量。