I am trying to UI test the command in my extension. When I run the test, it quits without any error message before reaching assert.equal() function.
The code of my test is as follows:
suite("Extension Tests", () => {
const fixtureFolderLocation = "../fixture/";
test("Wrap in parentheses", async () => {
const uri = vscode.Uri.file(
path.join(__dirname, fixtureFolderLocation, "fixture2.html"),
);
const document = await vscode.workspace.openTextDocument(uri);
const editor = await vscode.window.showTextDocument(document);
editor.selection = new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 4));
await vscode.commands.executeCommand("nkatex.wrapInParentheses");
const text = document.getText(new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 21)));
assert.equal(text, "\\left ( word\\right ) ");
});
});
Output of the test:
$ node ./out/test/runTest.js
Found .vscode-test/vscode-1.42.1. Skipping download.
[main 2020-02-16T15:06:03.708Z] update#setState idle
Extension Tests
Exit code: 0
Done
Done in 17.30s.
runTest.ts:
async function main() {
try {
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath: path.resolve(__dirname, "../../"),
extensionTestsPath: path.resolve(__dirname, "./suite"),
launchArgs: [
"--disable-extensions",
],
});
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
index.ts:
export const run = async (): Promise<void> => {
// Create the mocha test
const mocha = new Mocha({
ui: "tdd",
});
mocha.useColors(true);
const testsRoot = path.resolve(__dirname, "..");
const files = await async.glob("**/**.test.js", { cwd: testsRoot });
for (const file of files) {
mocha.addFile(path.resolve(testsRoot, file));
}
mocha.run((failureNumber) => {
if (failureNumber > 0) {
throw new Error(`${failureNumber} tests failed.`);
}
});
};
I have also tried using done() function and waiting a specific amount of time, but it did not help:
const sleep = (ms = 1000) => new Promise((resolve) => setTimeout(resolve, ms));
suite("Extension Tests", () => {
const fixtureFolderLocation = "../fixture/";
test("Wrap in parentheses", async (done) => {
const uri = vscode.Uri.file(
path.join(__dirname, fixtureFolderLocation, "fixture2.html"),
);
const document = await vscode.workspace.openTextDocument(uri);
const editor = await vscode.window.showTextDocument(document);
await sleep(2000);
editor.selection = new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 4));
await vscode.commands.executeCommand("nkatex.wrapInParentheses");
await sleep();
const text = document.getText(new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 21)));
assert.equal(text, "\\left ( word\\right ) ");
done();
});
});
The test exits at random places. Sometimes the tests passes correctly, but more often it quits before assertion. I believe this has something to with the code being asynchronous, but I have seen similar code in other tests, like here.
Related
when I test my tests on GOERLI network, it shows an Error that reads: 1) Raffle Unit Tests
"before each" hook for "works with live Chainlink Keepers and Chainlink VRF, we get a random winner":
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (node_modules/#nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context. (test/staging/Raffle.staging.test.js:15:38)
const { inputToConfig } = require("#ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")
developmentChains.includes(network.name)
? describe.skip
: describe("Raffle Unit Tests", function () {
let raffle, raffleEntranceFee, deployer
beforeEach(async function () {
deployer = (await getNamedAccounts()).deployer
await deployments.fixture(["all"])
raffle = await ethers.getContract("Raffle", deployer)
vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
raffleEntranceFee = await raffle.getEntranceFee()
})
describe("fulfillRandomWords", function () {
it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
// enter the raffle
console.log("Setting up test...")
await deployments.fixture(["mocks"])
const startingTimeStamp = await raffle.getLastTimeStamp()
const accounts = await ethers.getSigners()
console.log("Setting up Listener...")
await new Promise(async (resolve, reject) => {
// setup listener before we enter the raffle
// Just in case the blockchain moves REALLY fast
raffle.once("WinnerPicked", async () => {
console.log("WinnerPicked event fired!")
try {
const recentWinner = await raffle.getRecentWinner()
const raffleState = await raffle.getRaffleState()
const winnerEndingBalance = await accounts[0].getBalance()
const endingTimeStamp = await raffle.getLastTimeStamp()
await expect(raffle.getPlayer(0)).to.be.reverted
assert.equal(recentWinner.toString(), accounts[0].address)
assert.equal(raffleState, 0)
assert.equal(
winnerEndingBalance.toString(),
winnerStartingBalance.add(raffleEntranceFee).toString()
)
assert(endingTimeStamp > startingTimeStamp)
resolve()
} catch (error) {
console.log(error)
reject(error)
}
})
// Then entering the raffle
console.log("Entering Raffle...")
const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
await tx.wait(1)
console.log("Ok, time to wait...")
const winnerStartingBalance = await accounts[0].getBalance()
// and this code WONT complete until our listener has finished listening!
})
})
})
})
Can anyone help me out with these, here's the link to my repo: https://github.com/anooj1/hardhat-raffle
I'm working with Playwright, cucumber and Javascript. I'm facing the next issues below:
page.type: selector: expected string, got object
page.click: selector: expected string, got function
And many similar error messages.
this is the profile.cjs class, where the data is located:
const wrongEmailFormat = 'eyftqeiuyfqwiyfiwqfywqgfywqguddwqguy'
const existingEmail = 'amalg12#gmail.com'
module.exports = { wrongEmailFormat , existingEmail };
This is my profile-page.cjs:
const { secondaryUrl } = require("../config.cjs");
const { wrongEmailFormat , existingEmail } = require("../data/profile.cjs")
const should = require('chai').should(); //Chai assertion
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
const profileTitle = async () => await page.$('//h2[contains(text(),\'My Profile\')]')
const communicationTab = async () => await page.$('//button[#id=\'headlessui-tabs-tab-:R5l6:\']')
const currentEmail = async () => await page.$('#current-email')
const updateEmail = async () => await page.$('#cla9ruxam000w3b630t1c9dl4')
class ProfilePage {
async navigateToProfilePage() {
await page.goto(secondaryUrl)
await delay(2000)
}
async profilePageDisplayed() {
should.exist(profileTitle)
}
async communicationTabDisplayed() {
should.exist(communicationTab)
}
async currentEmailFieldDisplayed(){
should.exist(currentEmail)
}
async updateEmailFieldDisplayed(){
should.exist(updateEmail)
}
async updateEmailWrongFormat(){
//await page.keyboard.press(updateEmail().type(wrongEmailFormat))
//await updateEmail().click()
//await page.click(updateEmail, { force: true })
//await page.fill(wrongEmailFormat).toString()
//await page.waitFor(updateEmail())
//await page.click(updateEmail, { force: true }).toString()
//await page.fill(updateEmail(), wrongEmailFormat).toString()
//await page.dispatchEvent(updateEmail()).click
//await updateEmail().keys(wrongEmailFormat)
//await delay(3000)
}
}
module.exports = { ProfilePage };
updateEmailWrongFormat is all with comments, because I have tried in many ways, but without success.
Could anybody help me with this, please?
The error was the next:
All the selectors included in the profile-page were using the "WebdriverIO" format, so I did the next:
1.- Take all the selectors and move them to a new folder(selectors) inside a new class: profile-selectors with the next format:
module.exports = {
profileTitle: '//h2[contains(text(),\'My Profile\')]',
communicationTab: '//button[#id=\'headlessui-tabs-tab-:R5l6:\']',
currentEmail:'#current-email',
updateEmail:'//html[1]/body[1]/div[1]/div[1]/div[2]/main[1]/div[1]/div[2]/' +
'div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/input[1]'
};
After this, import in the Page object class and use them:
const { profileTitle, communicationTab, currentEmail, updateEmail} = require('../selectors/profile-selectors')
I know there are many xpaths, but much of the webelements do not have identifiers, or any others are dynamic elements.
Im new to Discod.js v13. I get this error
(async () => {
^
TypeError: (intermediate value) is not a function
This is the code i think its the problem
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
If you need the full code:
const { Client, Intents, Collection } = require("discord.js")
const fs = require("fs")
const {REST} = require("#discordjs/rest");
const {Routes} = require("discord-api-types/v9");
const client = new Client({
intents:[
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const BotName = "TestBot"
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
const commands = []
client.commands = new Collection()
for(const file of commandFiles){
const command = require("./commands/"+file)
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command)
}
client.once("ready", applicationId =>{
console.log(`${BotName} is now online`)
const CLIENT_ID = client.user.id
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
try{
if(process.env.ENV === "production"){
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
})
console.log("Success command register globally")
}else{
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID), {
body: commands
})
console.log("Success command register locally")
}
}catch(err){
console.log(err)
}
})();
})
client.on("interaction", async interaction =>{
if(!interaction.isCommand()) return
const command = client.commands.get(interaction.commandName)
if(!command) return
try{
await command.execute(interaction);
}catch(err){
console.log(err)
await interaction.reply({
content: "ERROR" + err,
ephemeral:true
})
}
})
client.login("MyToken")
As said in my comment, this is a ASI (automatic semicolon insertion) related error. I checked it, and after putting a semicolon after }).setToken("MyToken"); it worked fine.
Always use semicolons to avoid these mistakes.
I'm using this function to test my server that creates as many websocket connections and checks when my game starts. However no matter the timeout I assign, it hangs on JestJS. On the browser - Firefox, Edge Chromium it works perfectly fine.
function checkGameStart(numberOfBots) {
return new Promise((resolve, reject) => {
let clients = [];
let connection = [];
for (let i = 0; i < numberOfBots; i++) {
clients.push(new WebSocket('ws://127.0.0.1:8080'));
connection.push(false);
clients[i].onmessage = (msg) => {
let data = JSON.parse(msg.data);
if (data.title === "gameStarted") {
connection[i] = true;
checkAllClientsReady();
}
}
clients[i].onerror = (err) => reject(err);
}
function checkAllClientsReady() {
if (!(connection.includes(false))) {
resolve(true);
closeAllConnections();
}
}
function closeAllConnections() {
for (let i = 0; i < clients; i++) {
clients[i].close()
}
}
});
}
Does anyone know why it happens what I can do to make sure it doesn't happen again.
Test code;
test('Check the game starts', () => {
return expect(checkGameStart(4)).resolves.toBe(true);
});
I refactored your code a little bit and added a WebSocket server using ws NPM package on the test setup:
const { WebSocketServer } = require('ws')
const port = 8080
const wss = new WebSocketServer({ port })
beforeAll(() => {
wss.on('connection', (ws) => {
ws.send(JSON.stringify({ title: 'gameStarted' }))
})
})
afterAll(() => {
wss.close()
})
async function checkGameStart(numberOfBots) {
await Promise.all(
new Array(numberOfBots).fill(null)
.map(() => new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://localhost:${port}`)
ws.onmessage = ({ data }) => {
const { title } = JSON.parse(data)
if (title === 'gameStarted') {
ws.close()
resolve()
}
}
ws.onerror = (err) => {
ws.close()
reject(err)
}
}))
)
return true
}
test('Check the game starts', async () => {
await expect(checkGameStart(4)).resolves.toBe(true);
});
$ npx jest
PASS ./websocket.test.js
✓ Check the game starts (64 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.708 s, estimated 1 s
Ran all test suites.
This only works if Jest is also configured to use a jsdom test environment:
// jest.config.js
module.exports = {
testEnvironment: "jsdom",
};
Otherwise, the WebSocket constructor will be undefined since it is only available on web browser environments and, by default, Jest runs in node environment.
I have this code :
const { Logger } = require ("telegram/extensions");
const { TelegramClient } = require ("telegram");
const { StringSession } = require ("telegram/sessions");
const { NewMessage } = require ("telegram/events");
const { NewMessageEvent } = require ("telegram/events/NewMessage");
const { Message } = require ("telegram/tl/custom/message");
const input = require('input'); // npm i input
const puppeteer = require('puppeteer-extra');
async function eventHandler(event, browser) {
//get event.message, ....
const page = await browser.newPage();
}
const client = new TelegramClient(
new StringSession(stringSession),
apiId,
apiHash,
{ connectionRetries: 5 }
);
(async () => {
console.log('Loading interactive example...')
const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--shm-size=2gb', '--start-maximized', '--disable-features=IsolateOrigins,site-per-process', '--disable-web-security'], headless: true});
await client.start({
phoneNumber: "+33...",
password: async () => await input.text('password?'),
phoneCode: async () => await input.text('Code ?'),
onError: (err) => console.log(err),
});
console.log('Telegram bot connected');
console.log(client.session.save());
client.addEventHandler(eventHandler, new NewMessage({}), browser);
})();
I want to pass the browser variable to the eventHandler function.
I try like that, but it does not work, browser came "undefined" in eventHandler.
How pass the browser variable to my eventHandler?
Not sure what is the signature of client.addEventHandler but assuming it takes a single param event, you could try replacing your last line with something like:
client.addEventHandler(
(event) => eventHandler(event, browser),
new NewMessage({}),
);