Importing AMD module in to Mocha test - javascript

I am using Mocha to test code exported as AMD module. Running mocha test gives me following error.
ReferenceError: define is not defined
at Object.<anonymous> (/home/malintha/projects/...../xxx.js:1:63)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
The source which is tested as floows
define(['lodash', 'log', './yyy'], function(_, log, YYY) {
var xxxy = function() {
};
..............
});
And the mocha test
var expect = require("chai").expect;
var sourceGenVisitor = require("../../xxx")
describe("", function() {
describe("", function() {
it("Checks generated source", function() {
...................
});
});
});
How can I fix this issue ?

You can use amd-loader. I used it for years in a project of mine that was structured as a collection of AMD modules. Install with:
`npm install amd-loader`
It then needs to be loaded before any AMD module. In general:
require("amd-loader");
For Mocha you can use the argument --require amd-loader. You can put it in your test/mocha.opts file if you don't want to have to remember typing it over and over.

If you run mocha test with the typescript. Maybe you do this:
Install amd-loader:
npm install amd-loader --save
Run mocha test:
mocha src/**/*test.ts --require ts-node/register -r amd-loader

Related

How to provide test ESModule implementation in mocha test?

I have a mocha test which tests my code. My code uses another "core" npm package (which uses CommonJS modules). One of "core" the files ("synchronizer.js" file) requires "prefs" modules which is assumed to be provided at some point:
const {Prefs} = require("prefs");
In the mocha test i'd like to implement this "prefs" module, so i've created "prefs.mjs" file (with exports that "synchronizer.js" expects). However during the test i have the following error:
Error: Cannot find module 'prefs'
Require stack:
- /Users/developer/Documents/dev/src/project/node_modules/core/lib/synchronizer.js
- /Users/developer/Documents/dev/src/project/node_modules/core/lib/index.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1026:15)
at Module._load (node:internal/modules/cjs/loader:872:27)
at Module.require (node:internal/modules/cjs/loader:1092:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/developer/Documents/dev/src/project/node_modules/core/lib/synchronizer.js:26:17)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
at Module.load (node:internal/modules/cjs/loader:1068:32)
at Module._load (node:internal/modules/cjs/loader:909:12)
at Module.require (node:internal/modules/cjs/loader:1092:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/developer/Documents/dev/src/project/node_modules/core/lib/index.js:33:24)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
at Module.load (node:internal/modules/cjs/loader:1068:32)
at Module._load (node:internal/modules/cjs/loader:909:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
My project structure:
\sdk
\test
\unit
\ prefs
\prefs.mjs
\test.js
I run the tests (package.json):
"dependencies": {
...
"core": "^0.10.1",
...
},
"scripts": {
...
"unittest": "mocha --recursive ./test/unit/*.js",
...
}
}
test.js looks as follows:
describe("Section1", function() {
beforeEach(async function() {
await configureTestEnv();
// TODO: set "prefs" module
// TODO: set "io" module
// TODO: set "info" module
});
describe("subscriptions", function() {
it("throws if no condition is achieved", async function() {
...
I can run the tests (which does not include "core") successfully, so the testing works in general.
I suspect i have to use smth like webpack or babel, but i'd like to keep it clean and not using any deps or intermediate build steps if possible.
Should i pass modules directories paths to mocha to let node.js somehow find it?
Ended up using webpack and generating a module with aliased modules including prefs.

Detox issue: BUILD FAILED Ld build/Build/Products/Debug-iphonesimulator

I'm trying to use Wix/Detox to test my react-native app (the iOS version). I have successfully followed the instructions (up until "detox build") at https://github.com/wix/detox/blob/master/docs/Introduction.GettingStarted.md
However, when running "detox build" in my project directory, I get the following error:
** BUILD FAILED **
The following commands produced analyzer issues:
Analyze RNFIRMessaging.m
(1 command with analyzer issues)
The following build commands failed:
Ld build/Build/Products/Debug-iphonesimulator/<myAppName>.app/<myAppName> normal x86_64
(1 failure)
child_process.js:524
throw err;
^
Error: Command failed: xcodebuild -project ios/<myAppName>.xcodeproj -scheme <myAppName> -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build
at checkExecSyncError (child_process.js:481:13)
at Object.execSync (child_process.js:521:13)
at Object.<anonymous> (/Users/<myUserName>/Documents/react-native-projects/<myAppName>/node_modules/detox/local-cli/detox-build.js:26:6)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:423:7)
When running "detox test," I get the following error:
node_modules/.bin/mocha e2e --opts e2e/mocha.opts
detox info 09:31:22: server listening on localhost:50342...
detox info 1: Listing devices...
1) "before all" hook
0 passing (376ms)
1 failing
1) "before all" hook:
Error: field CFBundleIdentifier not found inside Info.plist of app binary at /Users/<myUserName>/Documents/react-native-projects/<myAppName>/ios/build/Build/Products/Debug-iphonesimulator/<myAppName>.app
at SimulatorDriver._callee2$ (node_modules/detox/lib/devices/SimulatorDriver.js:28:19)
at tryCatch (node_modules/regenerator-runtime/runtime.js:64:40)
at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:299:22)
at Generator.prototype.(anonymous function) [as throw] (node_modules/regenerator-runtime/runtime.js:116:21)
at step (node_modules/detox/lib/devices/SimulatorDriver.js:1:809)
at node_modules/detox/lib/devices/SimulatorDriver.js:1:1008
child_process.js:524
throw err;
^
Error: Command failed: node_modules/.bin/mocha e2e --opts e2e/mocha.opts
at checkExecSyncError (child_process.js:481:13)
at Object.execSync (child_process.js:521:13)
at Object.<anonymous> (/Users/<myUserName>/Documents/react-native-projects/<myAppName>/node_modules/detox/local-cli/detox-test.js:46:4)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:423:7)
I have an e2e folder in my project directory with three files: init.js, mocha.opts, and firstTest.spec.js.
firstTest.spec.js looks like this:
/* eslint-env node, mocha */
/* global element, expect, device, by */
describe('FiestTest', () => {
beforeEach(async () => {
await device.reloadReactNative()
})
it('Shoudl find the phoneInput field and the init value as "09"', async () => {
await expect(element(by.id('LoginPage-phoneInput'))).toBeVisible()
await element(by.id('LoginPage-phoneInput')).typeText('09991234567')
await expect(element(by.id('LoginPage-loginGuideTxt'))).toBeVisible()
await element(by.id('LoginPage-loginBtn')).tap()
})
it('Dummy1"', async () => {
await device.reloadReactNative()
})
it('Dummy2', async () => {
await device.reloadReactNative()
})
it('Dummy3', async () => {
await device.reloadReactNative()
})
})
init.js looks like this:
/* eslint-env node, mocha */
require('babel-polyfill')
const detox = require('detox')
const config = require('../package.json').detox
before(async () => {
await detox.init(config)
})
after(async () => {
await detox.cleanup()
})
And mocha.opts looks like this:
--recursive --timeout 120000 --bail
Your help is highly appreciated!
I ran the following command and it solved the build issue:
watchman watch-del-all; npm start -- --reset-cache
This solved the issue for me:
detox clean-framework-cache && detox build-framework-cache
I have faced this issue while implementing detox in my react native project.
I have fixed it just by using latest fixing the project.pbxproj file
basically fixing the license configuration.

UI test with mocha and coffee script

I am setting up test case environment with the help of Getting started with Selenium WebDriver for node.js
I have installed all dependencies but still unable to run sample test case given in above blog:
selenium = require 'selenium-webdriver'
chai = require 'chai'
chai.use require 'chai-as-promised'
expect = chai.expect
before ->
#timeout 10000
#driver = new selenium.Builder()
.withCapabilities(selenium.Capabilities.chrome())
.build()
#driver.getWindowHandle()
after ->
#driver.quit()
describe 'Webdriver tutorial', ->
beforeEach ->
#driver.get 'http://bites.goodeggs.com/posts/selenium-webdriver-nodejs-tutorial/'
it 'has the title of the post in the window\'s title', ->
expect(#driver.getTitle()).to.eventually.contain
'Getting started with Selenium Webdriver for node.js'
it 'has publication date', ->
text = #driver.findElement(css: '.post .meta time').getText()
expect(text).to.eventually.equal 'December 30th, 2014'
it 'links back to the homepage', ->
#driver.findElement(linkText: 'Bites').click()
expect(#driver.getCurrentUrl()).to.eventually.equal 'http://bites.goodeggs.com/'
Running above test case with:
mocha JavaScript_test.coffee --compilers coffee:coffee-script/register
I get following error:
module.js:471
throw err;
^
Error: Cannot find module 'coffee-script/register'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /usr/local/lib/node_modules/mocha/bin/_mocha:337:3
at Array.forEach (native)
at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:329:19)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
I had the same problem, and I don't know when it change but the module coffee-script doesn't exist anymore.
The right package is coffeescript so the right command is :
mocha JavaScript_test.coffee --compilers coffee:coffeescript/register
But --compilers is deprecated so the new right syntaxe is :
mocha JavaScript_test.coffee --require coffeescript/register

Testing AMD modules with tape/ES6 unit tests?

I have a web app using:
ES5
RequireJS
Underscore
Backbone
jQuery
I have tried setting up a new unit test suite using:
ES6
Tape
Babel6
My AMD module app/util/stringUtil.js:
define([], function() {
'use strict';
return {
isBlank: function(str) {
return _.isUndefined(str) || _.isNull(str) || _.isString(str) && str.trim().length === 0;
}
};
});
My unit test in tapeTest.js:
import test from 'tape';
import sortUtil from 'app/util/stringUtil';
test('Testing stringUtil', (assert) => {
assert.ok(stringUtil.isBlank(' ')),
'Should be blank');
assert.end();
});
My .babelrc:
{
"presets": ["es2015"]
}
I run the test with tape:
tape -r babel-register tapeTest.js
I get the following error:
app/util/stringUtil.js:1
(function (exports, require, module, __filename, __dirname) { define([], function () {
^
ReferenceError: define is not defined
at Object.<anonymous> (stringUtil.js:1:23)
at Module._compile (module.js:434:26)
at loader (node_modules/babel-register/lib/node.js:126:5)
at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-register/lib/node.js:136:7)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (tapeTest.js:7:17)
at Module._compile (module.js:434:26)
I'm guessing tape doesn't recognize AMD modules? Can I fix this somehow? Maybe transpile AMD modules to CommonJS modules or something?
You can load AMD modules inside node with requirejs :_)
Read here: http://requirejs.org/docs/node.html
You have to import require and do a little config, something like this:
'use strict';
const test = require('tape');
const requirejs = require('requirejs');
requirejs.config({
baseUrl: __dirname,
nodeRequire: require
});
test('Test something', function (assert) {
requirejs(['app/util/stringUtil'], function (stringUtil) {
assert.ok(stringUtil.isBlank(' '), 'Should be blank');
assert.end();
});
});
I solved it by using karma, webpack and phantomjs launcher:
karma
karma-webpack
karma-phantomjs-launcher
karma-tap
tape
Webpack transpiles the ES6 unit tests to ES5 modules and karma launches and runs the tests in a phantomjs browser.

Webstorm UT - cannot find module

I'm trying to test simple code:
function div2(a, b) {
return a/b;
}
module.exports.div = div2;
And in examplesTestUnit.js file:
var calculator = require("./examples");
module.exports["div test"] = function(test) {
test.equal(calculator.div(6,2), 3);
test.equal(calculator.div(12,0), Infinity);
test.equal(calculator.div(0,3), 0);
test.done();
};
When I try to run test in Webstorm I got errors:
/usr/bin/node /tmp/nodeunit-intellij-starter.js /usr/lib/node_modules/nodeunit examplesTestUnit.js
Testing started at 02:42 ...
module.js:340
throw err;
^
Error: Cannot find module '/usr/lib/node_modules/nodeunit/deps/async'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at resolveAsyncModule (/tmp/nodeunit-intellij-starter.js:304:20)
at testIt (/tmp/nodeunit-intellij-starter.js:308:21)
at run (/tmp/nodeunit-intellij-starter.js:335:9)
at Object.<anonymous> (/tmp/nodeunit-intellij-starter.js:365:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
Process finished with exit code 8
I installed mocha for tests and mocha didnt gives me an errors, but there's still no results:
[DzikiChrzan#DzikiLaptopF untitled]$ mocha examplesTestUnit.js
0 passing (1ms)
[DzikiChrzan#DzikiLaptopF untitled]$
I have installed nodeunit in 0.8.6 version and I already tried to reinstall it.
Plus another error I recive in terminal:
[DzikiChrzan#DzikiLaptopF untitled]$ nodeunit --
/usr/lib/node_modules/nodeunit/lib/nodeunit.js:72
if (err) throw err;
^
Error: ENOENT, stat '/home/DzikiChrzan/WebstormProjects/untitled/--'
I'm using Fedora 22. How can I fix this?
Okay, I did it.
I downloaded and installed nodeunit using npm.
npm install -g n
n stable
Next thing I needed to do was manually indicate path to nodeunit module in WebStorm. In my case it was:
/home/DzikiChrzan/node_modules/nodeunit

Categories

Resources