I'm writing test code for VS Code Extension with mocha and puppeteer.
This code behaves oddly.
This test will change the result without editing the code.
Sometimes test is failed because timeout of const e = await global.page.waitForSelector("iframe", { timeout: 10000 });, and sometimes it succeeds.
Changing the value of the slowMo option of puppeteer.launch() after several timeouts may result in a successful test. (not every time)
How can I make this stable?
describe("test", () => {
before(async () => {
global.browser = await puppeteer.connect({
browserURL: 'http://127.0.0.1:9229',
defaultViewport: null,
slowMo: 10
});
global.page = (await global.browser.pages())[0];
});
after(async () => {
if (global.page) {
await global.page.close();
}
if (global.browser) {
global.browser.disconnect();
}
});
describe("open file", () => {
before(async () => {
// open file with my custom editor
const uri = Uri.file(path.join(__dirname, "test.pdf"));
await commands.executeCommand("vscode.open", uri);
// get editor's dom content
const e = await global.page.waitForSelector("iframe", { timeout: 10000 });
const ec = await editor.contentFrame();
const ee = await editorFrame.waitForSelector("iframe#active-frame", { timeout: 10000 });
const eec = await editorContent.contentFrame();
global.dom = eec;
});
after(async () => {
await commands.executeCommand("workbench.action.closeActiveEditor");
});
it("should have x", async () => {
const x = await global.doc.waitForSelector("#x", { timeout: 5000 });
assert.ok(x);
});
});
});
Related
Slow functions
Future<bool> verySlowFunction([Duration duration = const Duration(milliseconds: 2000)]) async{
await Future.delayed(duration, () {
debugPrint('run very slow function...');
});
return true;
}
bool verySlowFunction2(){
for(var index = 0; index <1000000000000; index ++){}
return true;
}
Actual test code
group('my timeout tests', () {
test('timeout test', ()async {
final result = await verySlowFunction() ;
expect(result, equals(true));
}, timeout: const Timeout(Duration(milliseconds: 300)));
test('timeout test2', (){
final result = verySlowFunction2() ;
expect(result, equals(true));
}, timeout: const Timeout(Duration(milliseconds: 500)));
},);
I expected to tests are failed as the slow functions has more time than timeout duration I set. But the tests succeed... How this happens?
I'm trying to setup testing my node with mongo app using Jest. I've set it up and copied their sample verbatim, which works fine, except when I call the db.close(); function. It gives me a TypeError: that db.close is not a function. This is directly out of their example:
import { MongoClient } from 'mongodb';
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
await db.close();
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});
I am trying to setup an integration test for apollo graphql and need to connect to my mongodb database but this doesnt seem to be working. See the below code:
const MongoClient = require('mongodb').MongoClient
const LOADER_URI = 'mongodb://localhost:27017'
describe('ApolloIntegrationTest', () => {
test('Test', () => {
MongoClient.connect(URI, (err, client) => {
if(err) throw err
const pulseCore = client.db('pulse-core')
console.log(pulseCore)
const books = pulseCore.collection('books')
console.log(books)
client.close()
})
})
});
When i run the test, i expected to see the console logs printing but nothing prints when the test finishes. Not sure what i am doing wrong here.
You can use beforeAll and afterAll to simplify this.
const MongoClient = require('mongodb').MongoClient;
const LOADER_URI = 'mongodb://localhost:27017'
describe('ApolloIntegrationTest', () => {
let connection;
beforeAll(async () => {
connection = await MongoClient.connect(LOADER_URI);
});
afterAll(async () => {
await connection.close();
});
test('Test', async () => {
const pulseCore = await connection.db('pulse-core');
console.log(pulseCore);
const books = pulseCore.collection('books');
console.log(books);
});
});
let result = await vscode.commands.executeCommand('workbench.action.tasks.build');
resolves immediately.
How can I await a build task with VS Code API?
I figured it out! Tasks cannot be awaited from vscode.tasks.executeTask, but we can await vscode.tasks.onDidEndTask and check if ended task is our task.
async function executeBuildTask(task: vscode.Task) {
const execution = await vscode.tasks.executeTask(task);
return new Promise<void>(resolve => {
let disposable = vscode.tasks.onDidEndTask(e => {
if (e.execution.task.group === vscode.TaskGroup.Build) {
disposable.dispose();
resolve();
}
});
});
}
async function getBuildTasks() {
return new Promise<vscode.Task[]>(resolve => {
vscode.tasks.fetchTasks().then((tasks) => {
resolve(tasks.filter((task) => task.group === vscode.TaskGroup.Build));
});
});
}
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('extension.helloWorld', async () => {
const buildTasks = await getBuildTasks();
await executeBuildTask(buildTasks[0]);
}));
}
Note that currently there is a bug #96643, which prevents us from doing a comparison of vscode.Task objects: if (e.execution.task === execution.task) { ... }
I think this depends on how the main command is executed in the extension.ts
Being new to JS/TS, I may be wrong here, but just trying to help:
make sure the vscode.command.registerCommand is not asyncronous, like below:
context.subscriptions.push(vscode.commands.registerCommand('extension.openSettings', () => {
return vscode.commands.executeCommand("workbench.action.openSettings", "settingsName");
}));
This would be compared to something async, like below:
context.subscriptions.push(vscode.commands.registerCommand('extension.removeHost', async (hostID) => {
const bigipHosts: Array<string> | undefined = vscode.workspace.getConfiguration().get('extension.hosts');
const newHosts = Hosts?.filter( item => item != hostID.label)
await vscode.workspace.getConfiguration().update('f5-fast.hosts', newBigipHosts, vscode.ConfigurationTarget.Global);
hostsTreeProvider.refresh();
}));
i'm not sure why i am receiving this. I am trying to create a simple test while using #hapi/crumb. i am only registering it once in my server.js.
const Path = require("path");
const hapi = require("hapi");
const inert = require("inert");
const vision = require("vision");
const Ejs = require("ejs");
const Crumb = require("#hapi/crumb");
const Blankie = require("blankie");
const Scooter = require("#hapi/scooter");
const routes = require("./routes");
// Configure the server
const server = hapi.Server({
host: "0.0.0.0",
port: process.env.PORT || 3000,
routes: {
files: {
relativeTo: Path.join(__dirname, "..", "public")
},
state: {
parse: true,
failAction: "ignore"
},
security: {
xframe: true,
noOpen: false
},
cors: {
origin: ["banglarelief.org"],
headers: ["Authorization"], // an array of strings - 'Access-Control-Allow-Headers'
exposedHeaders: ["Accept"], // an array of exposed headers - 'Access-Control-Expose-Headers',
additionalExposedHeaders: ["Accept"], // an array of additional exposed headers
maxAge: 60,
credentials: true // boolean - 'Access-Control-Allow-Credentials'
}
}
});
const plugins = async () => {
const pluginsToRegister = [
inert,
vision,
require("hapi-mobile-views"),
{ plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
Scooter,
{
plugin: Blankie,
options: {} // specify options here
}
];
await server.register(pluginsToRegister);
};
const init = async () => {
await plugins();
server.state("player", {
ttl: null,
clearInvalid: true,
isSecure: false
});
server.views({
engines: { ejs: Ejs },
path: `${__dirname}/views`,
layout: "layout"
});
await server.route(routes);
return server;
};
const start = async () => {
try {
await init();
await server.start();
} catch (err) {
console.log(err);
process.exit(1);
}
};
module.exports = { init, start };
My test file is very basic and i have tried to move around where the start should be called but it keep throwing same error.
'use strict';
const Lab = require('#hapi/lab');
const { expect } = require('#hapi/code');
const { afterEach, beforeEach, describe, it } = exports.lab = Lab.script();
const { init, start } = require('../src/server');
let server = start();
describe('GET /', () => {
//let server;
//server = start();
beforeEach(async () => {
//server = start();
});
afterEach(async () => {
//await server.stop();
});
it('responds with 200', async () => {
const res = await server.inject({
method: 'get',
url: '/'
});
expect(res.statusCode).to.equal(200);
});
});
I have been following https://hapijs.com/tutorials/testing?lang=en_US
The solution seems to work if you break up your plugins function into two parts. One part will init 3rd party plugins like #Hapi/*. The other function will init your 1st party plugins that you wrote. You will only init the 3rd party plugins in your start function.
It's critical that you include { once: true } because that will prevent your error. It will only initialize the plugin once, which will prevent your error. You cannot always specify { once: true } on 3rd party plugins. Thus, we have to handle that a different way. Since we moved all the 3rd party plugins to their own function, which is invoked on start, that should prevent 3rd party plugins from causing an issue of being reinitialized.
const hapiPlugins = async () => {
const pluginsToRegister = [
inert,
vision,
require("hapi-mobile-views"),
{ plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
Scooter,
{
plugin: Blankie,
options: {} // specify options here
}
];
};
const myPlugins = async () => {
await server.register([
allOfMyPlugins...
],
{
once: true //critical so that you don't re-init your plugins
});
};
const init = async () => {
server.state("player", {
ttl: null,
clearInvalid: true,
isSecure: false
});
server.views({
engines: { ejs: Ejs },
path: `${__dirname}/views`,
layout: "layout"
});
await server.route(routes);
return server;
};
const start = async () => {
try {
await hapiPlugins();
await init();
await server.start();
} catch (err) {
console.log(err);
process.exit(1);
}
};
Then, you should be able to call init in your test's before function. Use that server object to inject.