I'm writing a mocha test reporter that I want to use for customized Cypress tests documentation.
Which is the right way to debug reporter code (maybe with intellij Idea)?
EDIT
I tried to debug using intellij Idea tools, running cypress (both open and run) in debug mode.
I also tried the IntelliJ Cypress plugin pro version that allow test debugging.
I can't stop in breakpoints.
So I'm trying at least to print some debug log but I can't see my logs anywere.
I couldn't make it work with Cypress, but I could do with Mocha in VSCode.
Working example here
Steps to debug:
Install ts-node and typescript for your project: npm i ts-node typescript --save-dev
Create custom-reporter.ts in your src folder with this content: (taken from https://mochajs.org/api/tutorial-custom-reporter.html and modified slightly )
import { reporters, Runner, Suite, Test } from 'mocha';
const { EVENT_RUN_BEGIN, EVENT_RUN_END, EVENT_TEST_FAIL, EVENT_TEST_PASS, EVENT_SUITE_BEGIN, EVENT_SUITE_END } = Runner.constants;
// This reporter outputs test results, indenting two spaces per suite
export class CustomReporter extends reporters.Base {
private indents = 0;
constructor(runner: Runner) {
super(runner);
const stats = runner.stats;
runner
.once(EVENT_RUN_BEGIN, () => {
console.info('start');
})
.on(EVENT_SUITE_BEGIN, (suite: Suite) => {
this.increaseIndent();
})
.on(EVENT_SUITE_END, (suite: Suite) => {
this.decreaseIndent();
})
.on(EVENT_TEST_PASS, (test: Test) => {
// Test#fullTitle() returns the suite name(s)
// prepended to the test title
console.log(`${this.indent()}pass: ${test.fullTitle()}`);
})
.on(EVENT_TEST_FAIL, (test: Test, err: any) => {
console.log(`${this.indent()}fail: ${test.fullTitle()} - error: ${err.message}`);
})
.once(EVENT_RUN_END, () => {
console.log(`end: ${stats.passes}/${stats.passes + stats.failures} ok`);
});
}
private indent() {
return Array(this.indents).join(' ');
}
private increaseIndent() {
this.indents++;
}
private decreaseIndent() {
this.indents--;
}
}
We will compile custom-reporter.ts by ts-node at runtime, but we have to pass a .js to Mocha as a reporter.
Therefore we create index.js as follows and we export our reporter as follows:
module.exports = require("./src/custom-reporter").CustomReporter;
Add test script to your package.json if you want to run without debugging:
"scripts": {
"test": "mocha -r ts-node/register specs/*.spec.ts --reporter index"
},
Create .vscode/launch.json in your project root, and add the following code:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Mocha tests",
"cwd": "${workspaceRoot}",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-r",
"ts-node/register",
"--reporter",
"index",
"${workspaceFolder}/specs/**/*.spec.ts"
],
"protocol": "inspector",
"sourceMaps": true,
"console": "integratedTerminal"
},
]
}
Place some breakpoints in VSCode into src/custom-reporter.ts
In VSCode open the Run and Debug panel (Ctrl+Shift+D), select Debug Mocha tests and press the play button
This way you should be able to start the test running and hit your breakpoints in VSCode.
Cheers!
Related
I created a new Vue app using npm init vue#latest and selected Playwright for e2e tests. I removed firefox and webkit from projects in the playwright.config.ts file, so it will only use chromium.
Running npm run test:e2e works fine, the process exists with a success code.
When forcing the tests to fail by modifying the ./e2e/vue.spec.ts file the output is
but the process does not exit with an error code, it still opened browser windows and so CI environments would freeze.
I searched the docs for a specific flag e.g. "headless" and tried --max-failures -x but that didn't help.
How can I tell Playwright to run in headless mode and exit with an error code when something failed?
Since playwright.config.ts already makes use of process.env.CI I thought about replacing reporter: "html", with reporter: [["html", { open: !process.env.CI ? "on-failure" : "never" }]],
but which arguments should I add to the script "test:e2e:ci": "playwright test", to ensure process.env.CI is set?
Update
I tried to run the script inside my CI environment and it seems to work out of the box ( I don't know how it sets the CI environment flag but the pipeline did not freeze )
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Check if e2e tests are passing
run: npm run test:e2e
If any test fails it exists with an error code
It's serving the html report and asking to press 'Ctr+C' to quite.You can disable it using below configuration.
// playwright.config.ts
import { PlaywrightTestConfig } from '#playwright/test';
const config: PlaywrightTestConfig = {
reporter: [ ['html', { open: 'never' }] ],
};
export default config;
Refer - Report Doc
Issue - https://github.com/microsoft/playwright/issues/9702
To add to the answer above, you can set headless: true in the 'use' block of the config which is above the projects block. Anything set at that level will apply to all projects unless you specifically override the setting inside a project specific area:
// playwright.config.ts
import { PlaywrightTestConfig } from '#playwright/test';
const config: PlaywrightTestConfig = {
reporter: [ ['html', { open: 'never' }] ],
use: {
headless: true,
},
projects: [
{
name: 'chromium',
use: {
browserName: 'chromium',
},
},
},
};
export default config;
I'm having a storybook with vue3 and vite. I want to measure my code coverage via istanbul when I run playwright tests.
Therefore I configured my storybook vite under .storybook/main.ts as follows:
const config: StorybookViteConfig = {
....
typescript: {
check: false,
checkOptions: {},
},
framework: '#storybook/vue3',
core: {
builder: '#storybook/builder-vite',
},
...
async viteFinal(config, { configType }) {
return mergeConfig(config, {
plugins: [
istanbul({
include: 'src/*',
exclude: ['node_modules', 'test/'],
extension: ['.js', '.ts', '.vue'],
}),
],
....
})
},
}
export default config
When I run storybook in dev mode with start-storybook -p 6006 and execute my playwright tests afterwards, the code is instrumented (coverage is not null) and a code coverage is measured.
However, when I build storybook and start the static build afterwards with these commands: build-storybook && http-server storybook-static --port 6006, the website works fine, but the coverage variable doesn't exist and no code coverage is measured, when I run playwright tests there.
I want to measure my code coverage in the ci used the built storybook for that (see https://storybook.js.org/docs/react/writing-tests/test-runner#run-against-non-deployed-storybooks). Or is there any other way to run playwright tests and measure code coverage in the ci?
I have seen similar questions on Stack Overflow but I don't feel like we're having the same issue and its been one year for the last question with no answers.
I have followed the documentation and all my tests are working fine, but when I open 4 simulators to try parallel testing only one of them reacts.
package.json
{
...
"detox": {
"configurations": {
"ios.sim.debug": {
"binaryPath": "ios/build/AppName/Build/Products/Debug-iphonesimulator/AppName.app",
"build": "xcodebuild -project ios/AppName.xcodeproj -scheme AppName -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
"type": "ios.simulator",
"device": {
"type": "iPhone 11"
}
}
},
"test-runner": "jest --detectOpenHandles --verbose",
"runner-config": "tests/detox/jest.config.js"
}
}
tests/detox/jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['./init.ts']
};
init.ts
import { cleanup, init } from 'detox';
const adapter = require('detox/runners/jest/adapter');
const config = require('../../package.json').detox;
jest.setTimeout(90000);
jasmine.getEnv().addReporter(adapter);
beforeAll(async () => {
await init(config, { initGlobals: false });
}, 90000);
afterAll(async () => {
await adapter.afterAll();
await cleanup();
});
And here is the command I use to start tests, after having 4 IOS simulators running and ready
detox test -l warn -w 4 ./path-to-all-tests
Dependencies
MacOS catalina
xed version 11.4
detox: ^16.0.2
jest: ^24.9.0
ts-jest: ^24.1.0
--detectOpenHandles makes the test run synchronously.
from jest docs:
--detectOpenHandles
Attempt to collect and print open handles preventing Jest from exiting
cleanly. Use this in cases where you need to use --forceExit in order
for Jest to exit to potentially track down the reason. This implies
--runInBand, making tests run serially. Implemented using async_hooks. This option has a significant performance penalty and should only be
used for debugging.
https://jestjs.io/docs/cli
You must remove it to run tests in parallel
I have setup botium project according to direction given in https://chatbotsmagazine.com/5-steps-automated-testing-of-chatbots-in-eclipse-ef4c3dcaf233 and its working fine for single botium.json file.
but when i try to setup multiple connector together ex-
1)botium_dialog.json
{
"botium": {
"Capabilities": {
"PROJECTNAME": "jokes",
"CONTAINERMODE": "dialogflow",
"DIALOGFLOW_PROJECT_ID": "###",
"DIALOGFLOW_CLIENT_EMAIL": "###",
"DIALOGFLOW_PRIVATE_KEY": "###",
"DIALOGFLOW_USE_INTENT": false
}
}
}
2) botium_watson.json
{
"botium": {
"Capabilities": {
"PROJECTNAME": "IBM Watson Conversation Sample",
"SCRIPTING_UTTEXPANSION_MODE": "all",
"SCRIPTING_FORMAT": "xlsx",
"SCRIPTING_XLSX_STARTROW": 2,
"SCRIPTING_XLSX_STARTCOL": 1,
"CONTAINERMODE": "watson",
"WATSON_USER": "#",
"WATSON_PASSWORD": "#",
"WATSON_WORKSPACE_ID": "#"
}
}
}
in the same project but running 1 at a time using
mocha --reporter mochawesome --reporter-options
\"reportDir=reportsDialog,reportFilename=index.html,code=false\"
--convos ./spec/convo/dialog --config botium_dialog.json --exit spec "
its giving error
Error: Capability 'CONTAINERMODE' missing
at BotDriver._getContainer (node_modules\botium-core\src\BotDriver.js:316:13)
at async.series (node_modules\botium-core\src\BotDriver.js:154:30)
The "--convos" and the "--config" command line parameters are actually for the Botium CLI, not for mocha. You either switch your test scripts to Botium CLI, or you configure Botium in a way to use several configuration files and several convo directories. My recommendation would be to pack each section in an own subdirectory - so you have a "botium_dialog" and a "botium_watson" directory, each with it's own package.json, botium.json, spec/convo folders etc.
With some configuration changes, it is also possible to use your current folder structure.
Add multiple botium.spec.js in spec folder:
botium_dialog.spec.js:
const BotiumBindings = require('botium-bindings')
const bb = new BotiumBindings({ convodirs: [ './spec/convo/dialog' ] })
BotiumBindings.helper.mocha().setupMochaTestSuite({ bb })
botium_watson.spec.js:
const BotiumBindings = require('botium-bindings')
const bb = new BotiumBindings({ convodirs: [ './spec/convo/watson' ] })
BotiumBindings.helper.mocha().setupMochaTestSuite({ bb })
Add multiple test scripts to your package.json:
package.json:
...
"scripts": {
"test_dialog": "BOTIUM_CONFIG=botium_dialog.json mocha --reporter spec --exit spec/botium_dialog.spec.js",
"test_watson": "BOTIUM_CONFIG=botium_watson.json mocha --reporter spec --exit spec/botium_watson.spec.js"
}
...
Run both of the test scripts
For example:
npm run test_dialog
npm run test_watson
I have some protractor tests running on windows 10. Every time I launch the tests, a new chromedriver gets started but it never goes away and keep piling up in the task manager. Why's that? Whom should I file the bug on? webdriver, protractor, or selenium?
This happens even with an empty config/test
Only conf I have is
exports.config = {
framework: "jasmine",
plugins: [],
jasmineNodeOpts: {
defaultTimeoutInterval: 120000
},
beforeLaunch: function() {
},
onPrepare: function() {
},
afterLaunch: function(exitCode) {
},
capabilities: {
"browserName": "chrome"
},
suites: {
example: "spec.js",
}
}
and the spec.js is essentially an empty test
called using "test": "protractor tests/conf.js" inside the package.json through npm
I created a bat file with the commands to kill the chromedriver like below.
#echo off
taskkill /f /t /im chromedriver_2.38.exe
exit
At the protractor.config.js I used the beforeLaunch() method and in each execution, it will verify if there's some chromedriver instantiated and I can use only one instance.
For execute the bat file I used child_process. https://nodejs.org/api/child_process.html#
The code on protractor.config below:
const { exec } = require('child_process');
beforeLaunch() {
exec('endchromedriver.bat');
}