【发布时间】:2019-12-31 19:53:40
【问题描述】:
我正在尝试运行类似的东西
describe('REGISTRATION', async () => {
const response = await axios.post(url, params);
});
我的代码如下所示
describe('REGISTRATION', () => {
// success registration, check expected fields
test('SUCCESS', async () => {
const response = await axios.post(url, params);
const { status, statusText } = response;
expect(status).toBe(200);
expect(statusText).toBe('OK');
const { jwt, user } = response.data;
expect(typeof(jwt)).toBe('string');
expect(user).toEqual({
id: expect.any(Number),
username: expect.any(String),
email: expect.stringMatching(emailRegExp),
});
});
});
这可行,但是当出现错误时,我没有得到详细信息,这给了我错误。 我会得到类似的东西
expect(received).toEqual(expected) // deep equality
expect(user).toEqual({.......
所以我为什么要用async 代替describe 是因为我想做类似的事情
describe('REGISTRATION', async () => {
const response = await axios.post(url, params);
const { status, statusText } = response;
const { jwt, user } = response.data;
test('id', () => {
expect(Number.isInteger(user.id)).toBe(true);
});
test('username', () => {
expect(typeof(user.username)).toBe('string');
});
test('email', () => {
expect(user.email).toEqual(expect.stringMatching(emailRegExp));
});
});
这样我就可以在测试时详细了解每个错误。
有没有人知道这将如何工作,或者我想太多了,还有其他方法可以做到这一点?
【问题讨论】:
-
不,但你可以在 beforeEach 中这样做。
-
您想在哪里进行错误处理?在
describe里面还是外面??我不是说验证 -
@fubar 我有点困惑,你这是什么意思?
-
我指的是 Promise 回调中未处理的异常将导致 Promise 被拒绝。这意味着,如果某些东西返回一个 Promise 并且你抛出一个错误,你可以使用
try{ let x = await somethingAsync() } catch(err){ ... }捕获它。这将为你提供处理不同级别错误的选项。捕获错误的替代方法:somethingAsync().catch(err => { .... }) -
@fubar 我现在明白你的意思了,但这也行不通,或者认为你可以用完整的代码示例或小提琴写下答案?以这种方式尝试捕获仍然会显示相同的完整
receive, expected,而不是一个一个
标签: javascript unit-testing async-await jestjs