How can I use Jasmine with CucumberJS? - javascript

How can I use jasmine with cucumberjs ?
I tried this solution from https://stackoverflow.com/a/30763260/5453732
But I have always this error : TypeError: this.expect(...).toBe is not a function at World. (/myApp/tests/e2e/steps/main.step.js:33:79)
Line 39 :
this.expect(element(by.css('[data-el="' + field + '"]')).isPresent()).toBe(true);
app/modules/user/tests/e2e/user.feature
#user.feature
Feature: Login feature
As a user
I want authenticate my account
Scenario: Authentication success
Given I am on "#/" page
Given I check if "navbar-menu-user-module" is visible
Given I wait "3" seconds
/tests/e2e/steps/main.step.js
module.exports = function () {
this.World = require("../support/world.js").World;
this.path = '#/';
this.Given(/^I am on "?([^"]*)"? page$/, function (arg1, callback) {
browser.get(arg1);
callback();
});
this.Given(/^I wait "?([^"]*)"? seconds$/, function (arg1, callback) {
browser.sleep(3000);
callback();
});
this.Given(/^I check if "?([^"]*)"? is visible$/, function (field, callback) {
this.expect(element(by.css('[data-el="' + field + '"]')).isPresent()).toBe(true);
callback();
});
};
/tests/e2e/support/world.js
var World, chai, chaiAsPromised;
chai = require('chai');
chaiAsPromised = require('chai-as-promised');
World = function World(callback) {
chai.use(chaiAsPromised);
this.expect = chai.expect;
callback();
}
module.exports.World = World;
protractor.conf.js
/* protractor.conf.js */
exports.config = {
directConnect: true,
seleniumServerJar: 'node_modules/selenium-server/lib/runner/selenium-server-standalone-2.48.2.jar',
specs: [
'app/modules/user/tests/e2e/*.feature'
],
getPageTimeout: 30000,
capabilities: {
'browserName': 'chrome',
version: '',
platform: 'ANY'
},
onPrepare: function() {
var width = 1024, height = 800;
browser.get('#/');
browser.driver.manage().window().setSize(width, height);
},
framework: 'cucumber',
cucumberOpts: {
require: [
'tests/e2e/steps/main.step.js'
],
format: 'pretty', // or summary
keepAlive: false
},
onCleanUp: function() {}
};
and my html :
<a data-el="navbar-menu-user-module" href="./#/user">User Module</a>
package.json
{
"name": "myApp",
"version": "1.0.0",
"description": "myApp",
"dependencies": {
},
"devDependencies": {
"chai": "^3.3.0",
"chai-as-promised": "^5.1.0",
"jasmine-core": "~2.3.4",
...
"protractor": "^2.5.1",
"selenium-server": "^2.48.2",
"selenium-standalone": "^4.7.0",
"selenium-webdriver": "^2.48.0",
}
}

The key thing to remember is that CucumberJS and Jasmine are mutually exclusive. You can only use Jasmine's expect's in conjunction with the Jasmine framework. toBe() is a function that is provided by Jasmine's expect, which doesn't exist in your framework. That is why you are receiving the error you described.
Since you are using CucumberJS to structure your test you need to use a separate assertion library, the most popular one being Chai. You'll need to use a function provided by Chai for your assertion. In your case you'll probably want to use the equal() function. Also remember that Protractor's isPresent() function returns a promise, so you'll want to use the eventually chain provided by chai-as-promised. All together, the following assertion:
this.expect(element(by.css('[data-el="' + field + '"]')).isPresent()).toBe(true);
should be changed to:
this.expect(element(by.css('[data-el="' + field + '"]')).isPresent()).to.eventually.equal(true);

You can use our jasmine-expect library. We took out the expectation library from Jasmine and released it as a separate module.
https://www.npmjs.com/package/xolvio-jasmine-expect

Related

Protractor - Cucumber - JS - Undefined Steps

I'm facing the next situation with Cucumber in Protractor (With Webstorm)
When I try to run the only feature that I have, it displays the next message (I have already defined the steps in a class)
Undefined. Implement with the following snippet:
Given('I open the url {string}', function (string) {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
...
1 scenario (1 undefined)
4 steps (4 undefined)
0m00.000s
Process finished with exit code 1
This is my config file (conf.js)
exports.config = {
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'https://www.afphabitat.cl/portalPrivado_FIXWeb/public/login.htm',
ignoreSynchronization: true,
getPageTimeout: 60000,
allScriptsTimeout: 50000,
defaultTimeoutInterval: 30000,
specs: ['features/*.feature'],
cucumberOpts: {
compiler: [],
require: ['step_defs/*.js'],
dryRun : false,
tags: ['#wip'],
monochrome: true,
strict: true,
plugin: "json",
format: 'json:reports/cucumber-report.json',
resultJsonOutputFile: 'reports/cucumber-report.json'
},
multiCapabilities:
[{
'browserName': 'chrome',
chromeOptions: {
binary: process.env.CHROME_BIN,
args: ['--no-sandbox', '--start-maximized']
}
},
{
'browserName': 'firefox',
args: ['--no-sandbox','--start-maximized']
}],
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
}
}
Next one is my step definition file (step_defs_Login.js)
import { Given, Then, When } from "cucumber";
import { browser, by, element, } from 'protractor';
Given('I open the url {string}', function (string) {
browser.get(string);
// callback();
});
When('proceed to enter my username as {string}', function (string1) {
let username = element(by.id('j_username_input')).clear();
username = element(by.id('j_username_input')).sendKeys(string1);
// callback();
});
When('proceed to enter my password as {string}', function (string2) {
let password = element(by.id('j_password')).clear();
password = element(by.id('j_password')).sendKeys(string2);
// callback();
});
Then('I have been logged in successfully', function () {
element(by.id('button')).click();
// callback();
});
Don't forget the JSON File (package.json)
{
"name": "package",
"version": "1.0.0",
"description": "First Protractor Cucumber project",
"main": "conf.js",
"scripts": {
"test": "cucumberjs"
},
"keywords": [
"TAE"
],
"author": "zzz",
"license": "ISC",
"devDependencies": {
"cucumber": "^5.1.0",
"selenium-webdriver": "^4.0.0-alpha.5"
},
"dependencies": {
"protractor": "latest"
}
}
I don't know if this is necessary or not, but this is my Hooks file (hooks.js)
let {defineSupportCode} = require('cucumber');
defineSupportCode (function ({After, Before}){
Before(function () {
// return this.driver.manage().window().maximize()
return this.browser.manage().window().maximize();
})
After(function () {
return this.driver.quit()
})
});
I have installed the next ones:
Protractor version 5.4.2
Node version 10.16.3
NPM 6.9.0
This is the project structure:
And this is the Run Configurations
Can anybody please help me with this???
Have you got the string you are passing in the feature file enclosed in "double quotes"?
I open the url "myUrl"
Try
require: ['../step_defs/*.js']
or
require: ['./step_defs/*.js']
In cucumberOpts object
Looks like you are using Webstrom to work on this cucumber framework. As I know, Webstrom will find the respective step definition for that step automatically. Coming to the issue,
1) Open your feature file and check that particular step is showing as implemented or not
2) Try to replace {string} with regular expression (.*) which will accept any type of data and check same step in feature file- step
Check both above cases

An error was thrown in afterAll ReferenceError: module is not defined, Karma/Jasmine test error in nodejs

I'm trying to write tests for m nodejs simple application with karma and jasmine as a framework. I'm using karma-coverage for preprocessor.
Here is the structure of the project:
package.json
{
"name": "tests",
"version": "1.0.0",
"description": "tests with karma in jasmine framework",
"directories": {
"test": "test"
},
"scripts": {
"test": "karma start karma.conf.js"
},
"author": "",
"license": "MIT",
"devDependencies": {
"jasmine-core": "^3.4.0",
"karma": "^4.2.0",
"karma-chrome-launcher": "^3.1.0",
"karma-coverage": "^1.1.2",
"karma-jasmine": "^2.0.1"
}
}
karma.conf.js
// Karma configuration
// Generated on Sat Aug 17 2019 09:37:53 GMT+0500 (Uzbekistan Standard Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'js/*.js',
'test/*.test.js'
],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/*.test.js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
// optionally, configure the reporter
coverageReporter: {
type: 'html',
dir: 'coverage/'
}
})
}
Whenever I run npm test I'm getting the following error:
custom-lodash.js
class CustomLodash {
compact(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
if (!array[i] || array[i] === undefined || array[i] === null) {
continue;
}
this.push(array[i])(newArray);
}
return newArray;
}
}
let _ = new CustomLodash;
module.exports = {
compact: _.compact
};
custom-lodash.test.js
describe("CustomLodash", function () {
let utils;
//This will be called before running each spec
beforeEach(function () {
console.log('before each');
utils = new CustomLodash();
});
describe("when calc is used to peform basic math operations", function () {
it("creates an array with all falsey values removed", function () {
// expect(utils.compact([0, 1, false, 2, '', 3])).toBe([1, 2, 3]);
let compact = utils.compact([0, 1, false, 2, '', 3]);
console.log('before each in it is: ', compact);
expect(compact).toEqual([1, 2, 3]);
//console.log('is defined ', expect(compact).toEqual([1, 2, 3]));
});
})
});
As you can see, the console.log is giving output, which means the file is being read. But, when I call toBe() or toEqual() I can see that the output is undefined (checked this in console.log too).
Any help is really appreciated. I searched for many answers and realted questions, but can't fix this one.
I want to share with my solution to this case.
Adding browserify worked for me. Also, I added watchify to watch files for incremental compilation.
Browserify was born to make your Node code in the browser. Till date
it only supports the node flavour of commons (including JSON support)
and provides in-built shims for many node core modules. Everything
else is a different package.
Here is how my package.json looks like after adding packages to run my ES6 code both in browser and Node:
"dependencies": {
"browserify": "^16.2.3",
"jasmine-core": "^3.2.1",
"karma": "^4.2.0",
"karma-chrome-launcher": "^3.1.0",
"karma-browserify": "^5.3.0",
"karma-commonjs": "^1.0.0",
"karma-coverage": "^1.1.2",
"karma-jasmine": "^2.0.1"
"watchify": "^3.11.0"
}
Don't forget to add browserify in your karma.config.js configuration as follows:
add it to your frameworks list
add it your preprocessors list.
Example:
preprocessors: {
'src/**/*.js': ['coverage'],
'js/**/*.js': ['browserify'],
'test/**/*.[sS]pec.js': ['browserify']
}
One can solve this kind of problem with ES6 by building webpack, but as browserify is much more likely to work with minimal configuration I chose using it as a solution in this situation. Hope it will help someone.

Resolve Module has not been loaded yet error Babel async-await

I am using babeljs to transform my javascript code. I am using async-await to handle asynchronous ajax calls in jquery. I haven't been able to figure out from the Babeljs Documentation exactly what configurations I need in order to get this to work. Using the below configurations I am gettin the error
Module name "babel-polyfill" has not been loaded yet for context: _. Use require([])
What configuration changes (or code changes) do I need to make in order to correctly configure Babel? Any additional explanation of working with Babel/es2015+ would be appreciated.
.babelrc
{
"plugins": [ "transform-async-to-generator" ],
"presets": ["env"]
}
package.json
{
"dependencies": {
"#types/jquery": "^2.0.46",
"#types/papaparse": "^4.1.28",
"#types/xrm": "^8.2.5",
"babel-polyfill": "^6.23.0",
"bootstrap": "^3.3.7",
"papaparse": "^4.3.3",
"requirejs": "^2.3.3",
"vue": "^2.3.3"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-preset-env": "^1.5.2"
},
"name": "mypackage",
"private": true,
"scripts": {
"build": "babel WebResources -d build/CCSEQ"
},
"version": "1.0.0"
}
main.js (pre-babel)
/// <reference path="../node_modules/#types/jquery/index.d.ts" />
"use strict";
require("babel-polyfill");
requirejs.config({
paths: {
PapaParse: "/papaparse.min",
Constants: "/build/CCSEQ/Constants",
Model: "/build/CCSEQ/Model",
WebAPI: "/build/CCSEQ/WebAPI",
Xrm: "/build/CCSEQ/Xrm",
Vue: "/node_modules/vue/dist/vue"
}
})
require(["PapaParse", "Constants", "Model", "WebAPI", "Xrm", "Vue"], function (Papa, Constants, Model, WebAPI, Xrm, Vue) {
function ImportExpenseTransaction(data) {
let newExpenseTransactions = new Array();
let entityID = Xrm.Page.getCurrentEntityID();
data.forEach(async (expense) => {
if (expense[0] !== "PR EMP ID") {
let newExpenseTransaction = new Model.Entity();
newExpenseTransaction.Type = Constants.EntityType.ExpenseTransaction;
newExpenseTransaction.Attributes.push(new Model.EntityField("ccseq_employeeid",
await WebAPI.Get(new Model.QueryDetails(Constants.EntityType.SystemUser, expense[0], ["systemuserid"], [new Model.Condition("ccseq_chnnavid", expense[0], Constants.Condition.EQUALS)])),
Constants.EntityType.SystemUser));
newExpenseTransactions.push(newExpenseTransaction);
}
});
});
main.js (post-babel)
/// <reference path="../node_modules/#types/jquery/index.d.ts" />
"use strict";
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
require("babel-polyfill");
requirejs.config({
paths: {
PapaParse: "/node_modules/papaparse/papaparse.min",
Constants: "/build/CCSEQ/Constants",
Model: "/build/CCSEQ/Model",
WebAPI: "/build/CCSEQ/WebAPI",
Xrm: "/build/CCSEQ/Xrm",
Vue: "/node_modules/vue/dist/vue"
}
});
require(["PapaParse", "Constants", "Model", "WebAPI", "Xrm", "Vue"], function (Papa, Constants, Model, WebAPI, Xrm, Vue) {
function ImportExpenseTransaction(data) {
var _this = this;
var newExpenseTransactions = new Array();
var entityID = Xrm.Page.getCurrentEntityID();
data.forEach(function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(expense) {
var newExpenseTransaction;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(expense[0] !== "PR EMP ID")) {
_context.next = 32;
break;
}
newExpenseTransaction = new Model.Entity();
newExpenseTransaction.Type = Constants.EntityType.ExpenseTransaction;
_context.t0 = newExpenseTransaction.Attributes;
_context.t1 = Model.EntityField;
_context.next = 7;
return WebAPI.Get(new Model.QueryDetails(Constants.EntityType.SystemUser, expense[0], ["systemuserid"], [new Model.Condition("ccseq_chnnavid", expense[0], Constants.Condition.EQUALS)]));
case 7:
_context.t2 = _context.sent;
_context.t3 = Constants.EntityType.SystemUser;
_context.t4 = new _context.t1("ccseq_employeeid", _context.t2, _context.t3);
_context.t0.push.call(_context.t0, _context.t4);
newExpenseTransactions.push(newExpenseTransaction);
case 32:
case "end":
return _context.stop();
}
}
}, _callee, _this);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
});
One thing I can see is that you're not actually doing anything with
require("babel-polyfill")
as in require is returning the module's export for you to use. Simply having line 4 in main.js isn't enough.
That said I'm not sure exactly what you're supposed to do with that module in this context.
I ran into a polyfill issue with our test suite (we use karma) and had to work around it like this (from karma.conf.js)
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: [
'../../node_modules/babel-polyfill/dist/polyfill.js',
'./index.js'
],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
I had to add the relative path to polyfill.js (that lives in the babel-polyfill module under /dist) into the files property. Maybe you need to do something similar?
But you'll probably want to store the return value of require into something like
var polyfill = require("babel-polyfill")
and then reference that somewhere.
Hope this helps.
¯\_(ツ)_/¯
maybe even in paths add something like:
Polyfill: "/node_modules/babel-polyfill/dist/polyfill.js"

Load a web page into a headless Jasmine spec running PhantomJS

How do I read in a page from localhost into a headless Jasmine spec so test cases can work on the DOM elements?
My Gulp task is successfully running Jasmine specs for unit testing, and now I need to build integration tests to verify full web pages served from localhost. I'm using the gulp-jasmine-browser plugin to run PhantomJS.
Example:
gulpfile.js
var gulp = require('gulp');
var jasmineBrowser = require('gulp-jasmine-browser');
function specRunner() {
gulp.src(['node_modules/jquery/dist/jquery.js', 'src/js/*.js', 'spec/*.js'])
.pipe(jasmineBrowser.specRunner({ console: true }))
.pipe(jasmineBrowser.headless());
}
gulp.task('spec', specRunner);
spec/cart-spec.js
describe('Cart component', function() {
it('displays on the gateway page', function() {
var page = loadWebPage('http://localhost/'); //DOES NOT WORK
var cart = page.find('#cart');
expect(cart.length).toBe(1);
});
});
There is no loadWebPage() function. It's just to illustrate the functionality I believe is needed.
End-to-End testing frameworks like a Selenium, WebdriverIO, Nightwatch.js, Protractor and so on are more suitable in such case.
The gulp-jasmine-browser plugin still is about the Unit testing in the browser environment. It is not possible to navigate between pages.
I put together the following code that appears to work. Please feel free to check out my repo and confirm in your own environment.
package.json
{
"name": "40646680",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "gulp jasmine"
},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-jasmine-browser": "^1.7.1",
"jasmine": "^2.5.2",
"phantomjs": "^2.1.7"
}
}
gulpfile.js
(() => {
"use strict";
var gulp = require("gulp"),
jasmineBrowser = require("gulp-jasmine-browser");
gulp.task("jasmine", () => {
return gulp.src("test/*.js")
.pipe(jasmineBrowser.specRunner({
console: true
}))
.pipe(jasmineBrowser.headless());
});
})();
test/sampleJasmine.js
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
it("contains failing spec with an expectation", function() {
expect(true).toBe(false);
});
});
Execution
Bob Chatman#CHATBAG42 F:\Development\StackOverflow\40646680
> npm test
> 40646680#1.0.0 test F:\Development\StackOverflow\40646680
> gulp jasmine
[21:56:44] Using gulpfile F:\Development\StackOverflow\40646680\gulpfile.js
[21:56:44] Starting 'jasmine'...
[21:56:44] Jasmine server listening on port 8000
.F
Failures:
1) A suite contains failing spec with an expectation
1.1) Expected true to be false.
2 specs, 1 failure
Finished in 0 seconds
[21:56:49] 'jasmine' errored after 4.26 s
[21:56:49] Error in plugin 'gulp-jasmine-browser'
Message:
1 failure
npm ERR! Test failed. See above for more details.
Dependencies
node 7.2
npm 3.9.3
jasmine 2.5.2
phantomjs 2.1.7
gulp 3.9.1
jsdom to the rescue!
It turns out it's pretty easy to load a web page into a headless Jasmine spec... but you need to swap out PhantomJS for jsdom.
Strategy:
Use Jasmine's beforeAll() to call a function that will run JSDOM.fromURL() to request the web page.
Once the web page has been loaded into the DOM, expose window and jQuery for use in your test cases.
Finally, call done() to indicate the tests are now ready to run.
Make sure to close the window after the tests have run.
spec.js
const url = 'http://dnajs.org/';
const { JSDOM } = require('jsdom');
let window, $;
function loadWebPage(done) {
function handleWebPage(dom) {
function waitForScripts() {
window = dom.window;
$ = dom.window.jQuery;
done();
}
dom.window.onload = waitForScripts;
}
const options = { resources: 'usable', runScripts: 'dangerously' };
JSDOM.fromURL(url, options).then(handleWebPage);
}
function closeWebPage() { window.close(); }
describe('The web page', () => {
beforeAll(loadWebPage);
afterAll(closeWebPage);
it('has the correct URL', () => {
expect(window.location.href).toBe(url);
});
it('has exactly one header, main, and footer', () => {
const actual = {
header: $('body >header').length,
main: $('body >main').length,
footer: $('body >footer').length
};
const expected = { header: 1, main: 1, footer: 1 };
expect(actual).toEqual(expected);
});
});
Test output
Note: Above screenshot is from a similar Mocha spec since Mocha has a nice default reporter.
Project
It's on GitHub if you want try it out yourself:
https://github.com/dnajs/load-web-page-jsdom-jasmine
EDITED: Updated for jsdom 11

AVA Unit Test: Use gulp-ava to test global functions

I'm new on using AVA for JS unit tests and I immediately hit a rock:
My situation is that I want to run a gulp task to run the AVA tests and watch the test files, and in the test file I wrote I need to include the js file that contains the code to test.
The problem is that the file with the code to test is an old js file with all global functions, so needs to be shimmed somehow into an AMD module, but how I can do this without changing the original file?
gulpfile.js
var gulp = require("gulp");
var ava = require("gulp-ava");
var srcUnitTestFiles = ["**/*.tests.js", "!node_modules/*.js"];
gulp.task("unit-tests-exec", () =>
gulp.src(srcUnitTestFiles)
// gulp-ava needs filepaths so you can't have any plugins before it
.pipe(ava({ verbose: true }))
);
gulp.task("unit-tests-watch", () =>
gulp.watch(srcUnitTestFiles, ["unit-tests-exec"])
);
package.json
{
"name": "name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "ava"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ava": "^0.16.0",
"gulp": "^3.9.1",
"gulp-ava": "^0.14.0",
"jsdom": "^9.4.2"
},
"ava": {
"require": [
"./test/helpers/setup-browser-env.js"
]
}
}
firstTest.tests.js
import test from "ava";
// I need to import the js file to test
test.before(t => {
});
test("foo", t => {
t.pass();
});
test('bar', async t => {
const bar = Promise.resolve('bar');
t.is(await bar, 'bar');
});
Thanks!
I think you mean UMD, not AMD. AMD wouldn't work.
I suggest you follow our recipe on browser testing with jsdom.
You could do the following at the top:
global.document = require('jsdom').jsdom('<body></body>');
global.window = document.defaultView;
require('./your-lib');
And then you can access your library on the window global:
window.yourLib();
With yourLib being the method you attached to window in your library.

Categories