【问题标题】:Is it possible to use async + await inside describe?是否可以在描述中使用 async + await ?
【发布时间】: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


【解决方案1】:

尝试在“它”上使用异步(并尝试阅读这篇文章https://staxmanade.com/2015/11/testing-asyncronous-code-with-mochajs-and-es7-async-await/):

describe("REGISTRATION" , () => {
    it("Using an async method with async/await!", async function() {
            var result = await somethingAsync();
            expect(result).to.equal(something);                    
    });
});

另见https://mochajs.org/#asynchronous-code(有一个异步等待示例)

【讨论】:

  • 您不需要同时使用asyncdone。 Mocha 支持开箱即用的Promises,因此您可以从it 回调中返回Promiseasync 标记的函数总是返回 Promise
  • 这不是我所说的我的工作代码的样子吗?如果有错误,它不会详细显示每个错误
【解决方案2】:

所以在这里我有一个工作示例,我认为它至少可以回答您关于如何查看异步调用详细信息的问题。

首先是 jesting.js 文件,这样你就可以看到我只返回 Promises

const jesting = (()=>{
    function sum(a, b){
        return new Promise( (resolve)=>{
            setTimeout(()=>{
                resolve(a+b)
            },2000)
        })
    }

    function sub(a, b){
        return new Promise( (resolve,reject)=>{
            setTimeout(()=>{
                resolve(a-b)
            },2000)
        })
    }

    return {
        sum: sum,
        sub: sub
    }

})();

module.exports = jesting;

现在是 jesting.test.js

const jesting = require('./jesting.js');

describe("STUFF", () => {

    const standByMe = jesting.sum(3, 3)

    test('a plus b is x', async () => {
        expect(await standByMe).toBe(6);
    })

    test('a plus b is x', async () => {
        expect(await standByMe).toBe(7);
    })

    test('a minus b is x', async () => {
        expect(await jesting.sub(7, 2).then(res => { return res - 2 })).toBe(3);
    })
})

现在会发生什么??

因此描述将在开始时执行,standByMe 将设置为包含一个承诺,该承诺将在 2 秒后解析为 6,sub() 将返回一个承诺,该承诺将在 2 秒后解析为 5 但我们想要3 所以我们作弊:P

请注意,a+b 测试 await 相同的 Promise 在您的情况下只是一个。正如您在 sub 中看到的那样,您还可以在收到响应后对其进行操作。同样有效的是const standByMe = jesting.sum(3, 3).then(res=>{return res+1}),它将返回 7 的测试成功

结果

哦,async 的回调不支持describe,所以回答你的主要问题 => 不,但在测试中是的

【讨论】:

  • 非常感谢您的回答和演示。我知道你的意思,但是如果我使用 api 调用,那么我必须在每个 test 中调用我不想要的 api,我想,有一个叫做 mocks 的东西用来模拟我的 api 调用我还在想办法:(
  • 不,您可以使用const apiCall = axios.post(url, params) 调用 API 一次,您可以多次等待同一个 Promise 而无需再次调用。又名延迟承诺。
猜你喜欢
  • 1970-01-01
  • 2016-11-16
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多