问题
I'm trying to run a simple test in jasmine using puppeteer, however I can't get puppeteer to work when i use it in my test script:
const puppeteer = require('puppeteer');
describe("Jasmine puppeteer", function() {
let browser;
let page;
beforeAll(() => {
browser = await puppeteer.launch({headless: false});
page = await browser.newPage();
await page.goto('chrome://newtab');
await page.screenshot({path: 'a.png'});
})
it("jasmine puppeteer", () => {
expect(await page.title()).toBe("");
done();
});
afterAll(() => {
})
});
On running this script I get:
$ npm test spec/testspec.js
> test@0.0.1 test D:\sample
> jasmine "spec/testspec.js"
D:\sample\spec\testspec.js:10
browser = await puppeteer.launch({headless: false});
^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at D:\sample\node_modules\jasmine\lib\jasmine.js:93:5
npm ERR! Test failed. See above for more details.
npm test
simply points to jasmine
. The test works fine if i comment puppeteer related code.
回答1:
await
only works inside async function
.
beforeAll((done) => {
let screenshot = async function() {
browser = await puppeteer.launch({ headless: false });
page = await browser.newPage();
await page.goto('chrome://newtab');
await page.screenshot({ path: 'a.png' });
}
screenshot().then(done)
})
回答2:
Following the first answer I put all awaits
inside async
functions. However I still wasn't able to run the test script. Turns out async/await are not supported by jasmine according to this github issue, some of the comments do suggest workarounds to fix that.
Resulting in the working script:
const puppeteer = require('puppeteer');
function testAsync(specFunction) {
return (done) => {
specFunction().then(() => {
done();
}).catch((error) => {
done.fail(error);
});
};
}
describe("Jasmine puppeteer", function() {
let browser;
let page;
beforeAll(testAsync(async () => {
browser = await puppeteer.launch({headless: false});
page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'a.png'});
}));
it("jasmine puppeteer", testAsync(async () => {
expect(await page.title()).toBe("");
}));
afterAll(() => {
})
});
回答3:
your code should be like this ‘’’ it("jasmine puppeteer",async () => { expect(await page.title()).toBe(""); done(); }); ‘’’
来源:https://stackoverflow.com/questions/48497986/jasmine-not-working-with-puppeteer