How can I save in Dalekjs terminal - save

How can I save the content of the 'test' object after its opened?
for example:
module.exports = {
'Page title is correct': function (test) {
test
.open('http://google.com')
// save content of test the HTML DOM
.assert.title().is('Google', 'It has title')
.done();
}
};
or maybe to interact directly with phantomJS
It is possible?

Even if it is not the main purpose of DalekJS to do things like this, it is technically possible to do it like so:
module.exports = {
'Can store html': function (test) {
test.open('http://google.com')
.execute(function () {
this.data('htmlData', window.document.getElementsByTagName('html')[0].outerHTML);
})
.log.message(function () {
var data = test.data('htmlData');
var fs = require('fs');
fs.writeFileSync('nameOfTheFile.html', data);
return data;
})
.assert.title().is('Google', 'It has title')
.done();
}
};
We execute some in browser JavaScript using the execute method & pipe it over to node using the data('key', 'value') storage method.
We access this data later in our log.message method which runs in the node context. This enables us to load the FileSystem module & finally to store the captured html into a file.

Related

can we use the toHaveScreenshot() and toMatchSnaphot() out side the test

Can we use the toHaveScreenshot() and toMatchSnaphot() outside the test without using config file only simple install NPM i playwright in package.json
I have already one snapshot I want to compare snapshot using toHaveScreenshot() method but I am confused we can use outside the test context?
const { chromium } =require( "playwright");
const example = async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto("https://zversal.com/");
await page.toHaveScreenshot("zeversal.png", {
fullPage: false,
maxDiffPixelRatio: 0.24,
});
};
example();
Console reports error:
toHaveScreenshot() must be called during the test
I don't think this is possible. Afaik, toHaveScreenshot() is part of the #playwright/test package.
If I'm looking at the Page API docs there's no toHaveScreenshot() listed. I'd say it's only available in combination with Playwright Test and it's provided expect method.
await expect(page).toHaveScreenshot();
As similarly noted by stefan judis in his answer, toHaveScreenshot is an assertion matchers method provided by expect which comes from the Playwright Test library and is made to be used inside tests.
While that assertion can’t be used, you can still take screenshots using Playwright, and then compare them manually or with another tool.
I don't know if it's possible to use it outside of testing, but you can create a PlaywrightDevPage helper class to encapsulate common operations on the page.
Simple Usage =>
// models/PlaywrightDevPage.js
class PlaywrightDevPage {
/**
* #param {import('playwright').Page} page
*/
constructor(page) {
this.page = page;
this.getStartedLink = page.locator('a', { hasText: 'Get started' });
this.gettingStartedHeader = page.locator('h1', { hasText: 'Installation' });
this.pomLink = page.locator('li', { hasText: 'Playwright Test' }).locator('a', { hasText: 'Page Object Model' });
this.tocList = page.locator('article div.markdown ul > li > a');
}
async getStarted() {
await this.getStartedLink.first().click();
await expect(this.gettingStartedHeader).toBeVisible();
}
async pageObjectModel() {
await this.getStarted();
await this.pomLink.click();
}
}
module.exports = { PlaywrightDevPage };
More Info => PlaywrightDevPage

Run several insert/update at once with typeorm

I'm facing an issue with typeorm.
In order to init my database for my repository tests, I wanted to create a sql file with several inserts, and execute the file directly with the entity manager.
It seams that it allows only one query at the time.
Somebody has an idea how to digest directly an sql file in one execution?
Here is an example I'm trying to do.
(it works well with entities and saving them, but for more complicated tests, I'd rather use an sql file).
I don't want to use migration globally because I want all the tests to be independant.
describe('Lead time repository', () => {
let app: INestApplication;
let leadTimeRepository: LeadTimeRepository;
function populateDB() {
const initScript = fs.readFileSync(path.join(__dirname, 'populate.sql'), 'utf-8');
console.log(initScript);
leadTimeRepository.manager.query(initScript);
}
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [DatabaseModule, LeadTimeModule],
}).compile();
app = module.createNestApplication();
await app.init();
leadTimeRepository = app.get<LeadTimeRepository>(LeadTimeRepository);
populateDB();
});
afterAll(async () => {
await app.close();
});
describe('findLeadTimeForEvent', () => {
it('Should do something.', () => {
console.log('should do something');
});
});
});
Thanks by advance.

Playwright save storage state only for certain files

I currently have a test pack that has >50 files. 49 of the files will use the same authentication, so I have set up the below inside my playwright config file:
storageState: 'myauth.json',
This allows me to store the state and use it across all of the tests,
the issue becomes where I don't want to use this state in one of my tests. How would one go about this?
I'm aware I could pass the state into 49 of the files and ignore it for the one, but this seems like the wrong idea.
If you do not want to use any storageState in your 50th test, then you can use test.use({ storageState: undefined }); in that test:
import { test } from '#playwright/test';
import LoginPage from '../../page/LoginPage';
test.use({ storageState: undefined });
test('This test ignores the storageState and performs a fresh login', async ({ page }) => {
loginPage = new LoginPage(page);
await loginPage.login();
});
You can use fixtures and as default value set the one you use 49 times.
In that case when you are need other auth just overwrite it with keyword "use". It is described in playwright doc. https://playwright.dev/docs/test-fixtures
import { TodoPage } from './todo-page'; //In your case auth1 auth2
import { SettingsPage } from './settings-page';
// Declare the types of your fixtures.
type MyFixtures = {
todoPage: TodoPage;
settingsPage: SettingsPage;
};
// Extend base test by providing "todoPage" and "settingsPage".
// This new "test" can be used in multiple test files, and each of them will get the fixtures.
export const test = base.extend<MyFixtures>({
todoPage: async ({ page }, use) => {
// Set up the fixture.
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo('item1');
await todoPage.addToDo('item2');
// Use the fixture value in the test.
await use(todoPage);
// Clean up the fixture.
await todoPage.removeAll();
},
settingsPage: async ({ page }, use) => {
await use(new SettingsPage(page));
},
});
Default auth use as you you page in your tests.
And when you need to overwrite in your specific file spec.ts file just write:
test.use({ auth: 'reareAuth' });

Embeded Watson Virtual Agent chatbot missing response

I've created an html file with embedded Watson Virtual Agent chat bot, code similar below, with WVA strictly using the building core capabilities:
IBMChat.init({
el: 'ibm_chat_root',
baseURL: 'https://api.ibm.com/virtualagent/run/api/v1',
botID: '',
XIBMClientID: '',
XIBMClientSecret: ''
});
What I noticed is if I run the WVA in Preview mode, and have input "pay bill", the WVA can come back with two piece response, with first:
Accessing your account information...
and second the make payment:
Your account balance is $42.01 due on 5/17/2017. What would you like to do? (More options coming soon!)
However, if I enter the same in my HTML chatbot, the response only comes back with the first part:
Accessing your account information...
and second part never comes out.
Does anyone else experience the same problem?
The version in the "Preview" mode has some mock "action" handlers setup. Obviously, not every one of you users would owe $42! In the sample code on the github, the mock action handlers are not setup. There are examples on how to subscribe to those action events with handlers here: https://github.com/watson-virtual-agents/chat-widget/tree/master/examples/basic-actions-example
As of 5/31/17 you can cover all the built in actions using the code snippet below...
const config = { instance: null };
const getUserProfileVariablesMap = {
'bill_amount': '42.01',
'payment_due_date': (() => {
const currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
return `${currentDate.getMonth() + 1}/${currentDate.getDate()}/${currentDate.getFullYear()}`;
})(),
'authorized_users': 'Bob Everyman and Jane Doe'
};
const getUserProfileVariables = (data) => {
const variables = data.message.action.args.variables;
variables.forEach(v => {
const value = getUserProfileVariablesMap[v];
(value) ? config.instance.profile.set(v, value) : config.instance.profile.set(v, '[sample data]');
});
config.instance.sendSilently('success');
};
const success = () => config.instance.sendSilently('success');
const agent = () => config.instance.receive('On your own site you would run code to connect to an agent now.');
const accountSettings = () => config.instance.receive('On your own site you would run code to open the Account Settings page now.');
function registerActions(instance) {
config.instance = instance;
instance.subscribe('action:getUserProfileVariables', getUserProfileVariables);
instance.subscribe('action:updateAddress', success);
instance.subscribe('action:updateUserName', success);
instance.subscribe('action:updatePhoneNumber', success);
instance.subscribe('action:updateEmail', success);
instance.subscribe('action:payBill', success);
instance.subscribe('action:sendPaymentReceipt', success);
instance.subscribe('action:agent', agent);
instance.subscribe('action:openAccountSettingsPage', accountSettings);
};
window.IBMChatActions = {
registerActions: registerActions
};
// window.IBMChatActions.registerActions(window.IBMChat);
On the Administrative Preview, you are getting fake code stubs that handle action requests from the agent.
When one of these actions are invoked, the widget will print the "Processing..." message and then invoke all registered subscribers for that action. It is up to these registered subscribers to continue the conversation flow by silently sending "success", "failure", or "cancel" back to the server.
For example, the agent might pass down the "payBill" action. You would want to call your payment gateway, determine if it was successful, and then notify the agent of the result:
IBMChat.init(/* Settings */);
IBMChat.subscribe('action:payBill', function() {
var data = {
amount: IBMChat.profile.get('amount'),
card: {
number: IBMChat.profile.get('cc_number'),
// ... other private card data
}
};
$.post('https://www.myserver.com/payment-gateway', data)
.done( function() {
IBMChat.sendSilently('success');
})
.fail( function() {
IBMChat.sendSilently('failure');
});
});
Actions Documentation
https://github.com/watson-virtual-agents/chat-widget/blob/master/docs/DOCS.md#actions

Pass custom data to service worker sync?

I need to make a POST request and send some data. I'm using the service worker sync to handle offline situation.
But is there a way to pass the POST data to the service worker, so it makes the same request again?
Cause apparently the current solution is to store requests in some client side storage and after client gets connection - get the requests info from the storage and then send them.
Any more elegant way?
PS: I thought about just making the service worker send message to the application code so it does the request again ... but unfortunately it doesn't know the exact client that registered the service worker :(
You can use fetch-sync
or i use postmessage to fix this problem, which i agree that indexedDB looks trouble.
first of all, i send the message from html.
// send message to serviceWorker
function sync (url, options) {
navigator.serviceWorker.controller.postMessage({type: 'sync', url, options})
}
i got this message in serviceworker, and then i store it.
const syncStore = {}
self.addEventListener('message', event => {
if(event.data.type === 'sync') {
// get a unique id to save the data
const id = uuid()
syncStore[id] = event.data
// register a sync and pass the id as tag for it to get the data
self.registration.sync.register(id)
}
console.log(event.data)
})
in the sync event, i got the data and fetch
self.addEventListener('sync', event => {
// get the data by tag
const {url, options} = syncStore[event.tag]
event.waitUntil(fetch(url, options))
})
it works well in my test, what's more you can delete the memory store after the fetch
what's more, you may want to send back the result to the page. i will do this in the same way by postmessage.
as now i have to communicate between each other, i will change the fucnction sync into this way
// use messagechannel to communicate
sendMessageToSw (msg) {
return new Promise((resolve, reject) => {
// Create a Message Channel
const msg_chan = new MessageChannel()
// Handler for recieving message reply from service worker
msg_chan.port1.onmessage = event => {
if(event.data.error) {
reject(event.data.error)
} else {
resolve(event.data)
}
}
navigator.serviceWorker.controller.postMessage(msg, [msg_chan.port2])
})
}
// send message to serviceWorker
// you can see that i add a parse argument
// this is use to tell the serviceworker how to parse our data
function sync (url, options, parse) {
return sendMessageToSw({type: 'sync', url, options, parse})
}
i also have to change the message event, so that i can pass the port to sync event
self.addEventListener('message', event => {
if(isObject(event.data)) {
if(event.data.type === 'sync') {
// in this way, you can decide your tag
const id = event.data.id || uuid()
// pass the port into the memory stor
syncStore[id] = Object.assign({port: event.ports[0]}, event.data)
self.registration.sync.register(id)
}
}
})
up to now, we can handle the sync event
self.addEventListener('sync', event => {
const {url, options, port, parse} = syncStore[event.tag] || {}
// delete the memory
delete syncStore[event.tag]
event.waitUntil(fetch(url, options)
.then(response => {
// clone response because it will fail to parse if it parse again
const copy = response.clone()
if(response.ok) {
// parse it as you like
copy[parse]()
.then(data => {
// when success postmessage back
port.postMessage(data)
})
} else {
port.postMessage({error: response.status})
}
})
.catch(error => {
port.postMessage({error: error.message})
})
)
})
At the end. you cannot use postmessage to send response directly.Because it's illegal.So you need to parse it, such as text, json, blob, etc. i think that's enough.
As you have mention that, you may want to open the window.
i advice that you can use serviceworker to send a notification.
self.addEventListener('push', function (event) {
const title = 'i am a fucking test'
const options = {
body: 'Yay it works.',
}
event.waitUntil(self.registration.showNotification(title, options))
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
event.waitUntil(
clients.openWindow('https://yoursite.com')
)
})
when the client click we can open the window.
To comunicate with the serviceworker I use a trick:
in the fetch eventlistener I put this:
self.addEventListener('fetch', event => {
if (event.request.url.includes("sw_messages.js")) {
var zib = "some data";
event.respondWith(new Response("window.msg=" + JSON.stringify(zib) + ";", {
headers: {
'Content-Type': 'application/javascript'
}
}));
}
return;
});
then, in the main html I just add:
<script src="sw_messages.js"></script>
as the page loads, global variable msg will contain (in this example) "some data".

Resources