集成测试中异步删除断言失败的正确等待方案咨询
Playwright集成测试时序问题:删除操作断言失败
问题现象
运行Playwright集成测试时,删除标签的断言始终失败(实际值为1,期望值为0),但调试单步执行时断言可成功通过。推测核心原因是后端删除操作尚未完成,断言就已执行,属于异步时序问题。尝试为异步方法添加.GetAwaiter().GetResult()未解决问题。
测试代码(C#)
[Test] public async Task DeleteTagTest(IPage page) { // get the context TagsContext? tagsContext; using var scope = Fixture.Services.CreateScope(); }集中St丰core🛶 PrepareInner锦 feature挂/swinde controlled::: tagsContext = scope.ServiceProvider.GetRequiredService<TagsContext>(); if(tagsContext == null) { throw new Exception("Tags context is null"); } // Arrange // create the tag int tagID = tagsContext.CreateTag("tagNumber1", 1, "c40rj8f"); // Act // go to the scan page await page.GotoAsync(Fixture.ServerAddress + "Scan"); await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded); // find the delete button var deletebutton = await page.QuerySelectorAsync("#delete"); // invoke delete await deletebutton.ClickAsync(); await page.WaitForLoadStateAsync(LoadState.Load); // Assert // check that it got deleted Assert.AreEqual(0, tagsContext.Tags.Where(x => x.ID == tagID).ToList().Count); // This assert fails if run normally, but succeeds if debug and step through }
前端删除按钮AJAX逻辑
deleteTagBtn.addEventListener('click', (event) => { console.log(qrKey + ': ' + tagNumber); $.ajax({ url: `/api/Scans/Delete?QRKey=${qrKey}&tagNumber=${tagNumber}`, method: 'DELETE', success: function (response) { $('#output').html('Tag Deleted Successfully.'); }, error: function (xhr, status, error) { $('#output').html('Tag Deletion Failed.'); console.error(error); } }); });
已尝试的无效方案
按照Playwright官方建议,尝试等待页面元素变化(等待#output元素可见),但该操作导致测试崩溃:
var output = page.Locator("#output"); await output.WaitForAsync();
求助需求
如何正确等待删除操作的执行结果,确保后端删除完成后再执行断言?
内容的提问来源于stack exchange,提问作者BWhite
相关产品推荐
相关产品推荐

