如何登录异步/等待上下文

时间:2019-03-04 08:12:41

标签: javascript async-await jestjs puppeteer

我想知道为什么我的第二个console.log()没有将任何内容记录到控制台...

describe('Puppeteer', () => {
  it('Does not log', () => {
    (async () => {
      console.log('This logs'); // <- works
      const browser = await puppeteer.launch({
        headless: true,
        args: [
          '--incognito'
        ]
      });
      await console.log('This does not log'); // <- Does not work
      console.log('This does not log too'); // <- This neither
      const page = await browser.newPage();
      await page.goto('....');
      ....
      expect(a < b)
        .toEqual(true);
      browser.close();
    })();
  });
});  

是否有任何原因不能记录?

1 个答案:

答案 0 :(得分:3)

解决方案:这不起作用,因为您正在立即运行该块。确保传递一个不是自我执行的函数。

自我执行功能的一个例子是(()=>{})()。这会导致测试无法正确解决。

这是清理后的代码:

const puppeteer = require('puppeteer');
const assert = require('assert');

describe('Puppeteer', () => {
  it('Does log', async () => { // <== PASS THE FUNCTION HERE
      const browser = await puppeteer.launch({args: ['--incognito']});
      console.log('This logs now');

      const page = await browser.newPage();
      await page.goto('https://example.org');
      const title = await page.title();
      assert.equal(title, 'Example Domain');

      console.log('This logs too');
      await browser.close();
  })
});

结果:

enter image description here

问题有jest而不是mocha。这是jest和结果的代码。除了下一行,几乎是一样的

// assert.equal(title, 'Example Domain');
expect(title).toEqual('Example Domain');

结果:

enter image description here

(可选)如果要将日志堆叠在一起,则可以在运行--verbose=false时传递jest

enter image description here