Is it possible to have the JS code and the mocha tests in the same file? The purpose will be to have both the implementation and the tests in the same file when you just want to play with something, learn JS, prepare for an interview, etc.
The file will be executed in VSCode using Debug (F5).
function increment(n) {
return n + 1;
}
mocha.setup("bdd");
const { assert } = chai;
describe('Array', function () {
describe('#indexOf()', function () {
it('should increment', function () {
assert.equal(increment(1), 2);
});
});
});
mocha.run();
Trying to run this example which is how you run mocha tests in browser, I get an error "mocha is not defined"
I ran "npm install --save-dev mocha" and "npm install --save-dev chai".
The file is test1.js.
In app.js I have "require("./test1")".
The launch configuration is:
{
// 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": [
{
"name": "Launch Program",
"program": "${workspaceFolder}/app.js",
"request": "launch",
"skipFiles": [
"<node_internals>/**"
],
"type": "pwa-node"
}
]
}
After more googling I found the solution, your Debug launch.json file have to have the below configuration. Basically the program you need to launch is "${workspaceFolder}/node_modules/mocha/bin/_mocha".
You do not need any mocha commands in your JS file: mocha.setup("bdd"); mocha.run();
{
// 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": [
{
"name": "Mocha Tests",
"type": "pwa-node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/thon-ly-40-questions"
],
"skipFiles": [
"<node_internals>/**"
],
},
]
}
Related
I have section exports in my package.json:
"exports": {
"import": "./dist/a.es.js",
"require": "./dist/b.umd.js"
},
But for development, I would like to have different path:
"exports": {
"DEV": {
"import": "./src/a.es.js", // <---------- SRC
"require": "./src/b.umd.js" , // <---------- SRC
},
"PROD": {
"import": "./dist/a.es.js",
"require": "./dist/b.umd.js"
}
},
Is there any way how to use some env variable?
I was able to solve this using this setup
In the package that my program imports:
{
"name": "my-special-node-package",
"version": "1.0.0",
"license": "MIT",
"exports": {
".": {
"production": {
"require": "./prod/index.cjs.js",
"import": "./prod/index.esm.js"
},
"default": {
"require": "./index.cjs.js",
"import": "./index.esm.js"
}
},
}
}
And then in my program:
// index.js
const myPkg = require('my-special-node-package')
On production I use node --conditions=production index.js to execute the node program. Otherwise I use node index.js in dev mode.
Also, since I'm using TypeScript and since TypeScript is only really used during development time, I was able to change the default require/import values to point to a index.ts file.
{
// ....
"exports": {
".": {
"production": {
"require": "./dist/index.cjs.js",
"import": "./dist/index.esm.js"
},
"default": "./index.ts"
},
}
}
This setup allows for my local development to always TS files directly and not rely on each package to be built whenever it changes.
I managed to mock typeorm to an extent but then now I'm facing a strange issue that I'll illustrate here.
import { myEntity } from './entity';
import typeorm = require('typeorm');
describe('test suire'), () => {
let myRepository: typeorm.Repository<myEntity>;
test('my test case', () => {
typeorm.Repository = jest.fn().mockReturnValue({
createQueryBuilder: jest.fn().mockReturnValue({
where: jest.fn().mockReturnThis(),
getMany: jest.fn().mockReturnValue([]);
})
});
myRepository = new typeorm.Repository();
expect(myRepository.createQueryBuilder).toHaveBeenCalledTimes(0);
})
})
I have a package structure like this:
root/
package.json
project1/
package.json
src/
the_above_test.spec.ts
When I run node_modules/.bin/jest path_to_above_test.spec.ts from project1 it works. But when I run the same command from root I get:
Matcher error: received value must be a mock or spy function
Received has value: undefined at line:
expect(myRepository.createQueryBuilder).toHaveBeenCalledTimes(0);
The intention here is to debug the test from within VS Code. But since VS code is open at the root level, it executes the test from there. If there's no bug in my code, how can I tell VS Code to run the test from the project1 directory?
You can specify different jest configurations in your /.vscode/launch.json
Each configuration will have it's own working directory, specified using "cwd".
here's a working example:
{
// 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",
"name": "functions",
"request": "launch",
"program": "${workspaceFolder}/packages/functions/node_modules/jest/bin/jest",
"args": [
"./test/eventHooks.test.ts",
"--runInBand"
],
"cwd": "${workspaceFolder}/packages/functions",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"name": "functions",
"request": "launch",
"program": "${workspaceFolder}/packages/types/node_modules/jest/bin/jest",
"args": [
"./test/eventHooks.test.ts",
"--runInBand"
],
"cwd": "${workspaceFolder}/packages/types",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
I am working on an electron test application for windows.
The goal is an auto launching application which displays a popup message everytime the windows user logs in.
Scenario:
I'm executing npm start to package my code. (index.js +
package.json)
I execute the generated .exe which will popup my message. (so far so good, right?)
I sign out from windows (CTRL + L ALT + DEL if this is important) and sign in again to test the application.
The popup opens but the default electron welcome page, too.
package.json
{
"name": "test",
"description": "",
"version": "0.0.1",
"main": "index.js",
"scripts": {
"test": "electron .",
"start": "electron-packager . Test --platform=win32 --arch=x64 --overwrite"
},
"author": "",
"license": "MIT",
"build": {
"appId": "com.test.test",
"win": {
"target": "NSIS"
}
},
"dependencies": {
"auto-launch": "^5.0.5"
},
"devDependencies": {
"electron": "latest",
"electron-packager": "^12.1.1"
}
}
index.js
const {app, dialog} = require("electron");
const AutoLaunch = require("auto-launch");
app.on("ready", function(){
dialog.showMessageBox({ message: "We are ready to take off! :-)", buttons: ["OK"] });
let autoLaunch = new AutoLaunch({
name: "test"
// path: app.getPath("exe")
}).isEnabled().then((isEnabled) => {
if (!isEnabled){
autoLaunch.enable();
dialog.showMessageBox({ message: "AutoLaunch enabled.", buttons: ["OK"] });
}
else dialog.showMessageBox({ message: "AutoLaunch already enabled.", buttons: ["OK"] });
});
app.quit();
});
Edit: Found a problem that prevents the package.json being updated. A simple npm info resulted in a completely unexpected output.
Wow, totally forgot about this question.
The solution was following:
Update all dependencies.
Make sure, that the path to the .html / .js file is absolute and correct.
An absolute path start with a /
For example /files/index.html
That's how it works!
I am creating a Visual Studio Code extension and have read that in order to provide a functionality to the StatusBarItem onclick event I need to register a command for the status bar item. How do I do this? When I create a StatusBarItem using window.createStatusBarItem I get an object which doesn't seem to have any string as identifier but the command registering process requires a string as first argument and I am not sure how to associate it with the StatusBarItem.
I have used yeoman to bootstrap a JavaScript extension.
extension.js
const vscode = require('vscode');
const { exec } = require('child_process')
function activate(context) {
console.log('Thanks for installing me! Remember to add a script to run if you want this extension to do anything \
instersting at all :P');
// TODO: make status bar item clickable
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1000);
function runCommandAndUpdateStatusBarItem () {
// TODO: fetch command from settings
const command = 'git describe --dirty="-$USER"';
exec(`cd ${vscode.workspace.rootPath} && ${command}`, [], (error, stdout, stderr) => {
if (stdout) {
statusBarItem.text = `$(git-commit) ${stdout}`;
statusBarItem.show();
}
else {
vscode.window.showErrorMessage(stderr);
statusBarItem.hide();
}
});
}
statusBarItem.hide();
let disposable = vscode.commands.registerCommand('extension.sayHello', runCommandAndUpdateStatusBarItem);
context.subscriptions.push(statusBarItem);
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {
console.log('Oh...so, you hate me? Ok I go away now :(');
}
exports.deactivate = deactivate;
package.json
{
"name": "script-result-info",
"displayName": "Script Result Info",
"description": "Runs a script in shell and puts the result in the statusBar",
"version": "0.0.1",
"publisher": "emilioidk",
"engines": {
"vscode": "^1.23.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.sayHello"
],
"main": "./extension",
"contributes": {
"commands": [
{
"command": "extension.sayHello",
"title": "Hello world"
}
]
},
"scripts": {
"postinstall": "node ./node_modules/vscode/bin/install",
"test": "node ./node_modules/vscode/bin/test"
},
"devDependencies": {
"typescript": "^2.6.1",
"vscode": "^1.1.6",
"eslint": "^4.11.0",
"#types/node": "^7.0.43",
"#types/mocha": "^2.2.42"
}
}
When I create a StatusBarItem using window.createStatusBarItem I get an object which doesn't seem to have any string as identifier
It does not by default since it's optional, yes, but you can set command on it:
statusBarItem.command = 'extension.sayHello';
Check the API docs for StatusBarItem: https://code.visualstudio.com/docs/extensionAPI/vscode-api#StatusBarItem
My JSPM version: 0.17.0-beta.5.
My project is using ES6 style import statement using TypeScript.
So...
I installed angular-ui-router like so:
jspm install angular-ui-router
This saves the following lines to my package.json:
"jspm" {
"overrides": {
"github:angular-ui/ui-router#0.2.17": {
"directories": {
"lib": "release"
},
"format": "cjs",
"main": "angular-ui-router",
"registry": "jspm",
"dependencies": {
"angular": "^1.3.2"
},
"meta": {
"angular-ui-router.js": {
"deps": [
"angular"
]
}
}
},
// ... other stuff
Great! So it says the file that should be loaded is located in the release folder.
But in my browser, I load my jspm.conf.js file, which says:
SystemJS.config({
"packages": {
"github:angular-ui/ui-router#0.2.17": {
"map": {
"angular": "github:angular/bower-angular#1.4.9"
}
},
}
// ... little further
"map": {
"angular-ui-router": "github:angular-ui/ui-router#0.2.17"
}
So there is no notion there that SystemJS should look in the release folder as I mentioned above. Therefor, I can't import like
import 'angular-ui-router'
but only like
import angular-ui-router/release/angular-ui-router
How do I use the overrides from package.json in my SystemJS config file jspm.config.js which is loaded in the browser?