gpt4 book ai didi

javascript - 即使断言在柏树中失败,测试仍然成功

转载 作者:行者123 更新时间:2023-12-05 03:18:48 25 4
gpt4 key购买 nike

我正在通过 API 获取真实数据,然后像这样检查响应是成功还是失败。

{ message: "fail" }

如果消息失败,我想强制测试失败,同时我想检查状态是否正常。即使使用throw new Error,测试依然成功。

enter image description here

我的代码是这样的

describe('fetch Data', () => {
beforeEach(() => {
cy.visit('http://localhost:3000');
});

it('Fetch Data', () => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843').then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
}).catch((err) => {
throw new Error(err);
});
});
});

最佳答案

本质上,fetch() 和后续的 .then().catch() 不在 Cypress 队列上运行,所以它确实如此不知道什么时候测试结束。

您可以将 fetch() 转换为 cy.request() 来解决这个问题。

但要继续获取,请在 catch block 内使用 Mocha 的 done() 方法来发出测试结束信号

it('Fetch Data', (done) => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
.then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
done()
})
.catch((err) => {
throw new Error(err);
done()
})
})

删除 catch 子句也会让测试失败。

it('Fetch Data', () => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
.then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
})
})

关于javascript - 即使断言在柏树中失败,测试仍然成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73605653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com