Executing a function inside puppeteer context - mocha.js

So, basically, I'm writing tests for my app, and I'd like to run a function inside the puppeteer browser's context. This is what I've tried:
Test code:
const printBlah = () => {
console.log('blah');
};
describe('Printing blah', () => {
it('Should print "blah".', async () => {
await page.evaluate(() => printBlah());
});
});
The error I'm getting:
1) Printing blah
Should print "blah".:
Error: Evaluation failed: ReferenceError: printBlah is not defined
at __puppeteer_evaluation_script__:1:16
at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/ExecutionContext.js:93:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at ExecutionContext.evaluate (node_modules/puppeteer/lib/ExecutionContext.js:32:16)
-- ASYNC --
at ExecutionContext.<anonymous> (node_modules/puppeteer/lib/helper.js:82:19)
at DOMWorld.evaluate (node_modules/puppeteer/lib/DOMWorld.js:111:24)
-- ASYNC --
at Frame.<anonymous> (node_modules/puppeteer/lib/helper.js:82:19)
at Page.evaluate (node_modules/puppeteer/lib/Page.js:792:47)
at Page.<anonymous> (node_modules/puppeteer/lib/helper.js:83:27)
at /mnt/repos/r/p/src/p/index.spec.ts:124:16
at step (src/p/index.spec.ts:33:23)
at Object.next (src/p/index.spec.ts:14:53)
at /mnt/repos/r/p/src/p/index.spec.ts:8:71
at new Promise (<anonymous>)
at __awaiter (src/p/index.spec.ts:4:12)
at Context.<anonymous> (src/p/index.spec.ts:123:30)
at processImmediate (internal/timers.js:456:21)

Related

Angular jasmine how to spy an async spy method

I am new to writing test with async/await in angular.
I have the following code. The service method is an async method. The test fails saying component.options.length is 0.
Can anyone please help me how to fix the error so the options has got the value i set in spy?
Thanks
spec.ts
spySideNavService = jasmine.createSpyObj('SideNavService', [], {
setOrgUserDetails: () => {},
loadMenus: () =>
[
{
id: 'my-menu',
label: 'My Menu',
icon: 'far fa-envelope fa-2x',
url: 'url'
}
] as NavOption[]
});
describe('ngOnInit', () => {
it('should add navigation options', () => {
expect(component.options.length).toBeGreaterThan(0);
});
});
component:
ngOnInit(): void {
this.options = await this.sideNavService.loadMenus();
}
SideNavService:
async loadMenus(): Promise<NavOption[]> {
//logic
}
Tried answer given below but still not working:
describe('ngOnInit', () => {
it('should add navigation options', fakeAsync(() => {
// !! call tick(); to tell the test to resolve all promises
// before coming to my expect line
tick();
expect(component.options.length).toBeGreaterThan(0);
}));
});
You need to use fakeAsync/tick to control promises.
// !! add fakeAsync
it('should add navigation options', fakeAsync(() => {
// !! call tick(); to tell the test to resolve all promises
// before coming to my expect line
// !! call ngOnInit
component.ngOnInit();
console.log(component.options);
tick();
console.log(component.options);
expect(component.options.length).toBeGreaterThan(0);
}));
Before, the test would go to the await line and go back to the test for the expect because the await is saying to do this later. Now with the tick, we are saying if they are any promises created, resolve them before moving forward.
Also, I think you're missing a Promise.resolve on loadMenus.
loadMenus: () => Promise.resolve(
[
{
id: 'my-menu',
label: 'My Menu',
icon: 'far fa-envelope fa-2x',
url: 'url'
}
] as NavOption[])
I am thinking the Promise.resolve is required so it can be awaited.
edit
I don't think the done callback will help you.
You can try using await fixture.whenStable() to wait for the promise(s). Try this:
describe('ngOnInit', () => {
it('should add navigation options', async () => {
component.ngOnInit();
await fixture.whenStable();
expect(component.options.length).toBeGreaterThan(0);
});
});

Mocha Chai Sequelize: I can't make tests fail

I am trying to write test for a model in sequelize, but I do not understand why it is not failing
it('should find user by id', (done) => {
users.findByPk(2)
.then((retrievedUser) => {
expect(retrievedUser.dataValues).to.deep.equal('it should break');
done();
})
.catch((err) => {
console.log(`something went wrong [should find user by id] ${err}`);
done();
})
});
When I run the test the output is the following
something went wrong [should find user by id] AssertionError: expected { Object (id, email, ...) } to deeply equal 'it should break'
1 -__,------,
0 -__| /\_/\
0 -_~|_( ^ .^)
-_ "" ""
1 passing (40ms)
If someone want to watch the full code, I created a project
For an asynchronous Mocha test to fail, pass an error as an argument to the done callback function
it('should find user by id', (done) => {
users.findByPk(2)
.then((retrievedUser) => {
expect(retrievedUser.dataValues).to.deep.equal('it should break');
done();
})
.catch((err) => {
console.log(`something went wrong [should find user by id] ${err}`);
done(err);
})
});
Alternatively, use an async function without a callback:
it('should find user by id', async () => {
const retrievedUser = await users.findByPk(2);
try {
expect(retrievedUser.dataValues).to.deep.equal('it should break');
} catch (err) {
console.log(`something went wrong [should find user by id] ${err}`);
throw err;
}
});
That said, I wouldn't recommend logging the error message of failing tests, because that's what Mocha already does for you in a typical setup. So I would get rid of the try-catch block in the example above.
it('should find user by id', async () => {
const retrievedUser = await users.findByPk(2);
expect(retrievedUser.dataValues).to.deep.equal('it should break');
});

Failed: Cannot read property 'saveFullPageScreen' of undefined

I came across protractor-image-comparison and wanted to test it out.
I made a limited test based on the example of the website, and I get the error
Failed: Cannot read property 'saveFullPageScreen' of undefined.
The browser.imageComparison is not defined.
It's strange I get this error following the example. There is limited support for protractor so I ask it here.
----------------- test.spec.ts --------------
import { browser, } from 'protractor';
import { Urls, DashboardPage } from '../utils';
fdescribe('protractor-image-comparison desktop', () => {
beforeEach(async () => {
await Urls.gotoDashboard();
await DashboardPage.getVPoints();
// await DashboardPage.removeDebugInfo();
});
it('should save some screenshots', async() => {
// Save a full page screens
await .saveFullPageScreen('fullPage', { /* some options*/ });
});
it('should compare successful with a baseline', async() => {
// Check a full page screens
expect(await browser.imageComparison.checkFullPageScreen('fullPage', { /* some options*/ })).toEqual(0);
});
});
-------------- part of jasmine.ts ---------------
plugins: [
{
// The module name
package: 'protractor-image-comparison',
// Some options, see the docs for more
options: {
baselineFolder: join(process.cwd(), './baseline/'),
formatImageName: `{tag}-{logName}-{width}x{height}`,
screenshotPath: join(process.cwd(), '.tmp/'),
savePerInstance: true,
autoSaveBaseline: true,
blockOutToolBar: true,
clearRuntimeFolder: true,
// ... more options
},
},
],
Failures:
1) protractor-image-comparison desktop should save some screenshots
Message:
Failed: Cannot read property 'saveFullPageScreen' of undefined
Stack:
TypeError: Cannot read property 'saveFullPageScreen' of undefined
at Object.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:119:83)
at step (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:75:27)
at Object.next (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:24:53)
at c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:17:71
at new Promise (<anonymous>)
at __awaiter (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:3:12)
at UserContext.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:110:16)
at c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:112:25
at new ManagedPromise (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:1077:7)
at ControlFlow.promise (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2505:12)
From: Task: Run it("should save some screenshots") in control flow
at UserContext.<anonymous> (c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:94:19)
at c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:64:48
at ControlFlow.emit (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\events.js:62:21)
at ControlFlow.shutdown_ (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2674:10)
at c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2599:53
From asynchronous test:
Error
at Suite.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:109:5)
at Object.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:93:1)
at Module._compile (internal/modules/cjs/loader.js:868:30)
at Module.m._compile (c:\projects\vital10-frontend\node_modules\ts-node\src\index.ts:392:23)
at Module.m._compile (c:\projects\vital10-frontend\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (internal/modules/cjs/loader.js:879:10)
According to the docs you are missing browser.imageComparison before .saveFullPageScreen

Why am I receiving this warning in a cypress task?

I'm running a task to seed my database in a before hook. Cypress is complaining that
Cypress Warning: Cypress detected that you returned a promise in a test, but also invoked one or more cy commands inside of that promise.
Here is the task
import { seed } from '../../../src/server/db/seed'
const pluginHandler = on => {
on('task', {
'seed:db': () => {
return seed()
}
})
}
export default pluginHandler
This is the seed function
import { exec } from 'child_process'
import util from 'util'
const execP = util.promisify(exec)
export const seed = () => {
// Drop notes.
return execP('mongo starter_test --eval "db.notes.drop()"')
.then(async () => {
// Insert notes fixtures.
await execP(
'mongoimport --db starter_test --collection notes --file ./src/server/db/notes.json'
)
})
.then(() => {
return 0
})
}
And finally the test, which doesn't do anything yet
describe('My First Test', () => {
before(async () => {
await cy.task('seed:db')
})
it('Does not do much!', () => {
cy.visit(Cypress.env('HOST'))
})
})
I'm not, as far as I can see, using commands inside the promise as the warning suggests.
As far as I know, async should not be used inside Cypress before, or any other command (unless you install a 3rd-party lib).
Please try with before(() => cy.task('seed:db'))

Testing Twitter Flight Component with Jasmine

Having issues running Jasmine Test with Twitter Flight. I'm using the jasmine-flight Plugin.
Error(s)
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
TypeError: this.Component is not a constructor
at Object.setupComponent (/frontend/bower_components/jasmine-flight/lib/jasmine-flight.js:44:23)
at Object.<anonymous> (/frontend/test/spec/component_ui/list-spec.js:5:10)
TypeError: Cannot read property 'trigger' of null
at Object.<anonymous> (/frontend/test/spec/component_ui/list-spec.js:19:19)
Test Component
describeComponent('javascript/component_ui/list-ui', function() {
'use strict';
beforeEach(function() {
jasmine.getFixtures().fixturesPath = 'base/test/fixtures';
this.setupComponent(
readFixtures('list.html'),
{
listRightMenu: '.list-right',
listSortSelector: '.list-sort',
}
);
});
it('Show menu when button is clicked', function() {
console.log(this);
this.component.trigger(this.component.attr.listSortSelector, 'click');
expect(this.component.attr.listRightMenu).toBeVisible();
});
});

Resources