This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,21 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([], function () {
'use strict';
/**
* Function used to be a placeholder for mage-init directive.
*/
function fn() {
fn.testCallback.apply(fn, arguments);
}
/**
* Function whose call wll be tested.
*/
fn.testCallback = function () {};
return fn;
});
@@ -0,0 +1,15 @@
{
"base": {
"nodeId": "mage-init-node",
"dataAttr": "data-mage-init",
"containerId": "test-suite-container"
},
"fn": {
"nodeData": {
"tests/assets/apply/components/fn": {
"baz": "foo"
}
},
"timeout": 20
}
}
@@ -0,0 +1,22 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'tests/assets/tools',
'tests/assets/apply/components/fn',
'text!./config.json',
'text!./templates/node.html'
], function (tools, fnComponent, config, nodeTmpl) {
'use strict';
var preset;
preset = tools.init(config, {
'fn': nodeTmpl
});
preset.fn.component = fnComponent;
return preset;
});
@@ -0,0 +1,10 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div id="<%= containerId %>">
<div id="<%= nodeId %>"
<%= dataAttr %>='<%= JSON.stringify(nodeData) %>'></div>
</div>
@@ -0,0 +1,80 @@
{
"data": [
{
"img": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8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AEBIiBABASIgAgIEAEBIiBABASIgAgIEAEBIiBABASIgAgIEAEBIiBABASIgAgIEAEBIiBABASIgAAREAEBIiBABOR7K8AA+80DxRN6Ax4AAAAASUVORK5CYII="
}
],
"magnifierOpts": {
"eventType": "hover",
"enabled": "true",
"width": "10",
"height": "10",
"top": "265",
"left": "50%"
},
"options": {
"nav": "thumbs",
"width": "30",
"height": "20",
"loop": "true",
"keyboard": "true",
"allowfullscreen": "true",
"arrows": "false",
"thumbwidth": "90",
"thumbheight": "90",
"ratio": "1"
},
"fullscreen": {
"nav": false
},
"breakpoints": {
"alias": {
"conditions": {
"min-width": "0px",
"max-width": "1px"
},
"options": {
"options": {
"arrows": "true"
}
}
}
}
}
@@ -0,0 +1,18 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(function () {
'use strict';
return {
local: {
path: 'tests/assets/jsbuild/local',
result: 'internal module'
},
external: {
path: 'tests/assets/jsbuild/external',
result: 'external module'
}
};
});
@@ -0,0 +1,9 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([], function () {
'use strict';
return 'external module';
});
@@ -0,0 +1,9 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([], function () {
'use strict';
return 'internal module';
});
@@ -0,0 +1,56 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div class="panel header">
<!-- This markup portion is the source for Mobile View Navigation Menu -->
<ul class="header links">
<li class="greet welcome" data-bind="scope: 'customer'">
<span class="logged-in">Welcome, John Doe!</span>
</li>
<li class="customer-welcome active">
<span class="customer-name active" role="button">
<button type="button" class="action switch" data-action="customer-menu-toggle">
<span>Change</span>
</button>
</span>
<!-- Markup portion for Logged in customer -->
<div class="customer-menu" data-target="dropdown" aria-hidden="false">
<ul class="header links">
<li>
<a href="http://magento.store/account/" id="my-account">My Account</a>
</li>
<li class="link wishlist" data-bind="scope: 'wishlist'">
<a href="http://magento.store/wishlist/" id="my-wishlist">My WishList</a>
</li>
<li>
<a href="http://magento.store/orders/" id="my-orders">My Orders</a>
</li>
<li>
<a href="http://magento.store/addresses/" id="my-addresses">My Addresses</a>
</li>
<li class="link authorization-link" data-label="or">
<a href="http://magento.store/customer/account/logout/">Sign Out</a>
</li>
</ul>
</div>
<li class="link authorization-link" data-label="or">
<a href="http://magento.store/customer/account/logout/">Sign Out</a>
</li>
</li>
<!-- Markup portion for Logged out customer -->
<li class="link authorization-link" data-label="or">
<a href="http://magento.store/customer/account/login/">Sign In</a>
</li>
<li>
<a href="http://magento.store/customer/account/create/" id="create-account">Create an Account</a>
</li>
</ul>
</div>
<div id="store.links">
<!-- Navigation Menu for Mobile View will be cloned here from the source -->
</div>
@@ -0,0 +1,38 @@
<ul id="menu">
<li class="foo">Aberdeen</li>
<li class="foo">Ada</li>
<li class="foo">Adamsville</li>
<li class="foo"><span class="ui-icon ui-icon-print"></span>Addyston</li>
<li class="test-menu-item">
<a>Delphi</a>
<ul>
<li class="foo">Ada</li>
<li class="foo">Saarland</li>
<li class="foo">Salzburg</li>
</ul>
</li>
<li class="foo">Saarland</li>
<li>
<a>Salzburg</a>
<ul>
<li>Delphi
<ul>
<li class="foo">Ada</li>
<li class="foo">Saarland</li>
<li class="foo">Salzburg</li>
</ul>
</li>
<li>Delphi
<ul>
<li class="foo">Ada</li>
<li> - </li>
<li class="foo">Saarland</li>
<li></li>
<li class="foo">Salzburg</li>
<li>&ndash;</li>
</ul>
</li>
<li class="foo">Perch</li>
</ul>
</li>
</ul>
@@ -0,0 +1,8 @@
<div id="tabs">
<div id="title1" data-role="collapsible">
</div>
<div id="content1" data-role="content"></div>
<div id="title2" data-role="collapsible">
</div>
<div id="content2" data-role="content"></div>
</div>
@@ -0,0 +1,4 @@
<script id="translate-form-template" type="text/x-magento-template">
<form id="<%= data.id %>"><%= data.newTemplateVariable %></form>
</script>
<div data-role="translate-dialog"></div>
@@ -0,0 +1,51 @@
{
"base": {
"containerId": "test-suite-container",
"dataAttr": "data-mage-init"
},
"virtual": {
"scriptData": {
"*": {
"tests/assets/script/component": {
"config": {
"foo": "bar"
}
}
}
},
"scriptId": "virtual-selector"
},
"bySelector": {
"nodeData": {
"tests/assets/script/component": {
"data": {
"foo": {
"baz": "foo"
}
}
}
},
"scriptData": {
"#node-by-selector": {
"tests/assets/script/component": {
"data": {
"foo": {
"bar": "baz"
}
}
}
}
},
"merged": {
"tests/assets/script/component": {
"data": {
"foo": {
"baz": "foo",
"bar": "baz"
}
}
}
},
"nodeId": "node-by-selector"
}
}
@@ -0,0 +1,17 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'tests/assets/tools',
'text!./config.json',
'text!./templates/selector.html',
'text!./templates/virtual.html'
], function (tools, config, selectorTmpl, virtualTmpl) {
'use strict';
return tools.init(config, {
bySelector: selectorTmpl,
virtual: virtualTmpl
});
});
@@ -0,0 +1,15 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div id="<%= containerId %>">
<div
id="<%= nodeId %>"
<%= dataAttr %>='<%= JSON.stringify(nodeData) %>'></div>
<script type="text/x-magento-init">
<%= JSON.stringify(scriptData) %>
</script>
</div>
@@ -0,0 +1,11 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div id="<%= containerId %>">
<script id="<%= scriptId %>" type="text/x-magento-init">
<%= JSON.stringify(scriptData) %>
</script>
</div>
@@ -0,0 +1,18 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(function () {
'use strict';
return {
local: {
path: 'text!tests/assets/text/local.html',
result: '<!--\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<span>Local Template</span>'
},
external: {
path: 'text!tests/assets/text/external.html',
result: '<!--\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<span>External Template</span>'
}
};
});
@@ -0,0 +1,7 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<span>External Template</span>
@@ -0,0 +1,7 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<span>Local Template</span>
+74
View File
@@ -0,0 +1,74 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore'
], function (_) {
'use strict';
return {
/**
* Processes configuration for a testsuite.
*
* @param {(Object|String)} config - Suite configuration.
* @param {Object} tmplMap - Template map for test cases.
*/
init: function (config, tmplMap) {
var preset;
if (_.isString(config)) {
preset = JSON.parse(config);
}
this.applyBase(preset);
if (tmplMap) {
this.applyTmpls(preset, tmplMap);
}
return preset;
},
/**
* Extends first levell properties of provided object
* with a default configuration.
*
* @param {Object} data - Object to be modified.
*/
applyBase: function (data) {
var base = data.base = data.base || {};
_.each(data, function (item) {
_.defaults(item, base);
});
},
/**
* Renderes template based on template map and a source data.
*
* @param {Object} source - Data for a lookup.
* @param {Object} map - Template map.
*/
applyTmpls: function (source, map) {
_.each(map, function (tmpl, suite) {
suite = source[suite];
suite.tmpl = _.template(tmpl)(suite);
});
},
/**
* Removes element by provided id.
*
* @param {String} id - Id of the element.
*/
removeContainer: function (id) {
var node = document.getElementById(id);
if (node) {
node.parentNode.removeChild(node);
}
}
};
});
+38
View File
@@ -0,0 +1,38 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
'use strict';
require.config({
bundles: {
'mage/requirejs/static': [
'buildTools',
'jsbuild',
'statistician',
'text'
]
},
paths: {
'dev/tests/js/jasmine': '../../../../../../dev/tests/js/jasmine',
'tests': '../../../../../../dev/tests/js/jasmine',
'squire': '../../../../../../node_modules/squirejs/src/Squire'
},
shim: {
squire: {
exports: 'squire'
}
},
config: {
jsbuild: {
'../../../../../../dev/tests/js/jasmine/assets/jsbuild/local.js': 'define([], function () {\'use strict\'; return \'internal module\'; });'
},
text: {
'../../../../../../dev/tests/js/jasmine/assets/text/local.html': '<!--\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<span>Local Template</span>'
}
},
deps: [
'mage/requirejs/static'
]
});
+69
View File
@@ -0,0 +1,69 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
'use strict';
var tasks = [],
_ = require('underscore');
function init(grunt, options) {
var _ = require('underscore'),
stripComments = require('strip-comments'),
path = require('path'),
config,
themes,
file;
config = grunt.file.read(__dirname + '/settings.json');
config = stripComments(config);
config = JSON.parse(config);
themes = require(path.resolve(process.cwd(), config.themes));
if (options.theme) {
themes = _.pick(themes, options.theme);
}
tasks = Object.keys(themes);
config.themes = themes;
file = grunt.option('file');
if (file) {
config.singleTest = file;
}
enableTasks(grunt, config);
}
function enableTasks(grunt, config) {
var jasmine = require('./tasks/jasmine'),
connect = require('./tasks/connect');
jasmine.init(config);
connect.init(config);
grunt.initConfig({
jasmine: jasmine.getTasks(),
connect: connect.getTasks()
});
}
function getTasks() {
tasks = tasks.map(function (theme) {
return [
'connect:' + theme,
'jasmine:' + theme
];
});
return _.flatten(tasks);
}
module.exports = {
init: init,
getTasks: getTasks
};
@@ -0,0 +1,11 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
(function() {
var env = jasmine.getEnv(),
config = {random: false};
env.configure(config);
})();
@@ -0,0 +1,91 @@
{
"host": "http://localhost:<%= port %>",
"port": 8000,
"root": "dev/tests/js/jasmine",
"static": "pub/static",
/**
* Path to themes configuration module. Relative to Magento root.
* This node is replaced by formatted theme configuration by 'dev/tests/jasmine/spec_runner' module
*/
"themes": "dev/tools/grunt/configs/themes",
"files": {
"requireBaseUrl": "<%= static %>/<%= area %>/<%= name %>/<%= locale %>",
"compactMap" : "<%= static %>/<%= area %>/<%= name %>/<%= locale %>/requirejs-map.js",
/**
* Path to RequireJS library. Relative to "server.base" config.
*/
"requireJs": {
"quick": "<%= static %>/<%= area %>/<%= name %>/<%= locale %>/requirejs/require.js",
"compact": "<%= static %>/base/Magento/base/default/requirejs/require.js"
},
/**
* Overridden "grunt-contrib-jasmine" SpecRunner template.
*/
"template": "<%= root %>/spec_runner/template.html",
/**
* These files are included to the page in <head> right after "require.js" in declared sequence.
*/
"requirejsConfigs": {
"quick": [
"<%= static %>/<%= area %>/<%= name %>/<%= locale %>/requirejs-config.js",
"<%= root %>/require.conf.js",
"<%= root %>/tests/lib/**/*.conf.js",
"<%= root %>/tests/app/code/**/base/**/*.conf.js",
"<%= root %>/tests/app/code/**/<%= area %>/**/*.conf.js",
"<%= root %>/tests/app/design/<%= area %>/<%= name %>/**/*.conf.js"
],
"compact": [
"<%= static %>/<%= area %>/<%= name %>/<%= locale %>/requirejs-map.js",
"<%= static %>/base/Magento/base/default/mage/requirejs/baseUrlResolver.js",
"<%= static %>/<%= area %>/<%= name %>/<%= locale %>/requirejs-config.js",
"<%= root %>/require.conf.js",
"<%= root %>/tests/lib/**/*.conf.js",
"<%= root %>/tests/app/code/**/base/**/*.conf.js",
"<%= root %>/tests/app/code/**/<%= area %>/**/*.conf.js",
"<%= root %>/tests/app/design/<%= area %>/<%= name %>/**/*.conf.js"
]
},
/**
* Files that contain tests. These are loaded to the page via RequireJS after all RequireJS configuration files have been loaded to the page.
* The sequence is ignored.
*/
"specs": [
"<%= root %>/tests/lib/**/*.test.js",
"<%= root %>/tests/app/code/**/base/**/*.test.js",
"<%= root %>/tests/app/code/**/<%= area %>/**/*.test.js",
"<%= root %>/tests/app/design/<%= area %>/<%= name %>/**/*.test.js"
]
},
"server": {
/**
* Directory to serve files from
*/
"base": "./",
/**
* Strings, mentioned here are interpreted as regular expressions. Use this option to override server's
* default behaviour and serve matched urls "as is" from Magento root.
*/
"serveAsIs": [
"^\/_SpecRunner.html",
"^\/dev\/tests",
"^\/.grunt",
"^\/pub\/static",
"^\/node_modules"
],
"options": {
/**
* All options mentioned here are defaults for "connect" grunt task.
* "debug" option enables server logs
* "keepalive" makes "connect" task pause with set up spec server, which you can fetch by %host%:%port%/_SpecRunner.html address in browser
*/
"debug": false,
"keepalive": false
}
}
}
@@ -0,0 +1,64 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
'use strict';
var tasks = {};
function init(config) {
var serveStatic = require('serve-static'),
grunt = require('grunt'),
_ = require('underscore'),
path = require('path'),
ignoredPaths, middleware, themes, files, port;
port = config.port;
files = config.files;
themes = config.themes;
ignoredPaths = config.server.serveAsIs;
function serveAsIs(path) {
return ignoredPaths.some(function (ignoredPath) {
return new RegExp(ignoredPath).test(path);
});
}
middleware = function (connect, options, middlewares) {
var server = serveStatic(process.cwd());
middlewares.unshift(function (req, res, next) {
var url = req.url;
if (serveAsIs(url)) {
return server.apply(null, arguments);
}
return next();
});
return middlewares;
};
_.each(themes, function (themeData, themeName) {
var options = {
base: _.template(config.server.base)(themeData),
port: port++,
middleware: middleware
};
_.defaults(options, config.server.options);
tasks[themeName] = { options: options };
});
}
function getTasks() {
return tasks;
}
module.exports = {
init: init,
getTasks: getTasks
};
@@ -0,0 +1,95 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
'use strict';
var tasks = {},
_ = require('underscore');
function init(config) {
var grunt = require('grunt'),
expand = grunt.file.expand.bind(grunt.file),
staticMode = 'quick',
themes, root, staticDir, baseUrl, mapFile, host, port, files, requireJs;
root = config.root;
staticDir = config.static;
port = config.port;
files = config.files;
themes = config.themes;
_.each(themes, function (themeData, themeName) {
var specs,
configs,
render;
_.extend(themeData, {
root: root,
static: staticDir
});
host = _.template(config.host)({
port: port++
});
render = renderTemplate.bind(null, themeData);
mapFile = renderTemplate(themeData, files.compactMap);
baseUrl = renderTemplate(themeData, files.requireBaseUrl);
if (grunt.file.exists(mapFile)) {
staticMode = 'compact';
}
if (config.singleTest) {
files.specs = [config.singleTest];
}
specs = files.specs.map(render);
specs = expand(specs).map(cutJsExtension);
configs = files.requirejsConfigs[staticMode].map(render);
requireJs = renderTemplate(themeData, files.requireJs[staticMode]);
tasks[themeName] = {
src: configs,
options: {
host: host,
template: render(files.template),
templateOptions: {
baseUrl: baseUrl
},
vendor: requireJs,
junit: {
path: "var/log/js-unit/",
consolidate: true
},
/**
* @todo rename "helpers" to "specs" (implies overriding grunt-contrib-jasmine code)
*/
helpers: specs,
sandboxArgs: {
args: ['--no-sandbox', '--disable-setuid-sandbox'],
defaultViewport: {width: 400, height: 400, hasTouch: true}
}
}
};
});
}
function renderTemplate(data, template) {
return _.template(template)(data);
}
function cutJsExtension(path) {
return path.replace(/\.js$/, '');
}
function getTasks() {
return tasks;
}
module.exports = {
init: init,
getTasks: getTasks
};
@@ -0,0 +1,35 @@
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="<%= temp %>/jasmine_favicon.png">
<% css.forEach(function (style) { %>
<link rel="stylesheet" href="<%= style %>">
<script type="text/javascript">
var require = {
baseUrl: '<%= options.baseUrl %>'
};
</script>
<% }); %>
<% with (scripts) { %>
<% [].concat(polyfills, jasmine, '.grunt/grunt-contrib-jasmine/boot0.js', 'dev/tests/js/jasmine/spec_runner/jasmine-config.js', '.grunt/grunt-contrib-jasmine/boot1.js', vendor, src, reporters).forEach(function (script) { %>
<script type="text/javascript" src="<%= script %>"></script>
<% }); %>
<% } %>
<script type="text/javascript">
var jasmineBoot = window.onload;
window.onload = null;
require(<%= JSON.stringify(scripts.helpers) %>, jasmineBoot);
</script>
</head>
<body></body>
</html>
@@ -0,0 +1,58 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define([
'jquery',
'Magento_Backend/js/media-uploader'
], function ($) {
'use strict';
describe('Magento_Backend/js/media-uploader::_create()', function () {
beforeEach(function () {
window.Uppy = {
Uppy: jasmine.createSpy('Uppy'),
Dashboard: jasmine.createSpy('Dashboard'),
Compressor: jasmine.createSpy('Compressor'),
DropTarget: jasmine.createSpy('DropTarget'),
XHRUpload: jasmine.createSpy('XHRUpload')
};
window.FORM_KEY = 'form_key';
window.Uppy.Uppy.and.returnValue({
use: jasmine.createSpy('uppyUse'),
on: jasmine.createSpy('uppyOn')
});
window.byteConvert = jasmine.createSpy('byteConvert');
spyOn($.fn, 'appendTo');
$('<div>').mediaUploader();
});
it('Uppy instance should get created with correct options', function () {
expect(window.Uppy.Uppy).toHaveBeenCalledWith({
autoProceed: true,
onBeforeFileAdded: jasmine.any(Function),
meta: {
'form_key': jasmine.any(String),
isAjax: true
}
});
});
it('Uppy should get configured with necessary plugins', function () {
const uppyInstance = window.Uppy.Uppy.calls.mostRecent().returnValue;
expect(uppyInstance.use).toHaveBeenCalledWith(window.Uppy.Dashboard, jasmine.any(Object));
expect(uppyInstance.use).toHaveBeenCalledWith(window.Uppy.DropTarget, jasmine.any(Object));
expect(uppyInstance.use).toHaveBeenCalledWith(window.Uppy.XHRUpload, jasmine.any(Object));
});
});
});
@@ -0,0 +1,39 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'Magento_Backend/js/validate-store'
], function ($, StoreValidation) {
'use strict';
describe('Magento_Backend/js/validate-store', function () {
var form,
model;
beforeEach(function () {
form = $('<form />');
model = new StoreValidation();
});
it('widget extends jQuery object', function () {
expect($.fn.storeValidation).toBeDefined();
});
it('Check options setting', function () {
form.storeValidation();
expect(form.storeValidation('option', 'storeData')).toBe(null);
form.storeValidation({
'storeData': 'test1'
});
expect(form.storeValidation('option', 'storeData')).toBe('test1');
});
it('_needConfirm method', function () {
expect(model._needConfirm()).toEqual(true);
});
});
});
@@ -0,0 +1,62 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define(['Magento_Bundle/js/components/bundle-checkbox', 'uiRegistry'], function (BundleCheckbox, registry) {
'use strict';
describe('Magento_Bundle/js/components/bundle-checkbox', function () {
var unit,
typeMap = {
typeMap: {
select: 'radio',
radio: 'radio',
checkbox: 'checkbox',
multi: 'checkbox'
}
};
beforeEach(function () {
unit = new BundleCheckbox({
dataScope: 'bundle-checkbox',
elementTmpl: jasmine.createSpy(),
clearValues: jasmine.createSpy()
});
});
describe('test changeType method', function () {
it('Do not clear values for "multi" select type', function () {
spyOn(registry, 'get').and.returnValue(typeMap);
spyOn(unit, 'checked').and.returnValue(false);
unit.changeType('multi');
expect(unit.prefer).toBe('checkbox');
expect(unit.clearValues).not.toHaveBeenCalled();
});
it('Do not clear values for "radio" select type if item not checked', function () {
spyOn(registry, 'get').and.returnValue(typeMap);
spyOn(unit, 'checked').and.returnValue(false);
unit.changeType('select');
expect(unit.prefer).toBe('radio');
expect(unit.clearValues).not.toHaveBeenCalled();
});
it('Clear values for "radio" select type', function () {
spyOn(registry, 'get').and.returnValue(typeMap);
spyOn(unit, 'checked').and.returnValue(true);
unit.changeType('select');
expect(unit.prefer).toBe('radio');
});
});
});
});
@@ -0,0 +1,73 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'Magento_Bundle/js/price-bundle',
'Magento_Catalog/js/price-box'
], function ($) {
'use strict';
describe('Magento_Bundle/js/price-bundle', function () {
var htmlContainer;
beforeEach(function () {
htmlContainer = $('<div class="price-final_price" data-role="priceBox"><ul class="price-box"></ul></div>');
});
afterEach(function () {
htmlContainer.remove();
});
it('Widget extends jQuery object.', function () {
expect($.fn.priceBundle).toBeDefined();
});
it('Check _updatePriceBox method call.', function () {
spyOn($.mage.priceBundle.prototype, '_updatePriceBox');
htmlContainer.priceBundle();
expect($.mage.priceBundle.prototype._updatePriceBox).toEqual(jasmine.any(Function));
expect($.mage.priceBundle.prototype._updatePriceBox).toHaveBeenCalledTimes(1);
});
it('Check _updatePriceBox method call after priceBox was initialized.', function () {
spyOn($.mage.priceBundle.prototype, '_updatePriceBox').and.callThrough();
htmlContainer.priceBundle();
$('.price-box', htmlContainer).priceBox();
expect($.mage.priceBundle.prototype._updatePriceBox).toEqual(jasmine.any(Function));
expect($.mage.priceBundle.prototype._updatePriceBox).toHaveBeenCalledTimes(2);
});
it('Check _applyOptionNodeFix method doesn\'t call after priceBox initialization.', function () {
var optionConfig = {
optionConfig: {
prices: {}
}
},
priceConfig = {
priceConfig: 10
};
spyOn($.mage.priceBundle.prototype, '_applyOptionNodeFix').and.callThrough();
htmlContainer.priceBundle(optionConfig);
$('.price-box', htmlContainer).priceBox(priceConfig);
$('.price-box', htmlContainer).trigger('price-box-initialized');
expect($.mage.priceBundle.prototype._applyOptionNodeFix).toEqual(jasmine.any(Function));
expect($.mage.priceBundle.prototype._applyOptionNodeFix).toHaveBeenCalledTimes(2);
});
it('Check _updatePriceBox method call before priceBox was initialized.', function () {
spyOn($.mage.priceBundle.prototype, '_updatePriceBox').and.callThrough();
$('.price-box', htmlContainer).priceBox();
htmlContainer.priceBundle();
expect($.mage.priceBundle.prototype._updatePriceBox).toEqual(jasmine.any(Function));
expect($.mage.priceBundle.prototype._updatePriceBox).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,87 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define([
'Magento_Catalog/js/components/dynamic-rows-import-custom-options'
], function (DynamicRows) {
'use strict';
describe('Magento_Catalog/js/components/dynamic-rows-import-custom-options', function () {
var model, data;
beforeEach(function () {
model = new DynamicRows({
index: 'dynamic_rows',
name: 'dynamic_rows',
indexField: 'id',
dataScope: '',
rows: [{
identifier: 'row'
}]
});
data = [{
'options': [
{
'option_id': 1,
'option_type_id': 1,
'values': [{
'option_id': 1,
'option_type_id': 1,
'some_fake_value': 1
}]
},
{
'option_id': 2,
'option_type_id': 2,
'values': [{
'option_id': 2,
'option_type_id': 2
}]
}
]
}];
model.source = {
set: jasmine.createSpy()
};
model.insertData = jasmine.createSpy().and.returnValue([]);
});
describe('Check processingInsertData', function () {
it('Check with empty data.', function () {
model.processingInsertData();
expect(JSON.parse(JSON.stringify(model.cacheGridData))).toEqual([]);
expect(model.insertData).not.toHaveBeenCalled();
});
it('Check with empty options data.', function () {
data = [{
'options': []
}];
model.processingInsertData(data);
expect(JSON.parse(JSON.stringify(model.cacheGridData))).toEqual([]);
expect(model.insertData).not.toHaveBeenCalled();
});
it('Check with fake imported custom options data.', function () {
model.processingInsertData(data);
expect(model.insertData).toHaveBeenCalled();
expect(JSON.parse(JSON.stringify(model.cacheGridData[0]))).toEqual({
'option_type_id': 1,
'position': 1,
'values': [{
'some_fake_value': 1
}]
});
expect(JSON.parse(JSON.stringify(model.cacheGridData[1]))).toEqual({
'option_type_id': 2,
'position': 2,
'values': [{}]
});
});
});
});
});
@@ -0,0 +1,85 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define([
'underscore',
'uiRegistry',
'Magento_Catalog/js/components/product-ui-select',
'ko',
'jquery'
], function (_, registry, Constr, ko, $) {
'use strict';
describe('Magento_Catalog/js/components/product-ui-select', function () {
var obj,
originaljQueryAjax;
beforeEach(function () {
originaljQueryAjax = $.ajax;
obj = new Constr({
name: 'productUiSelect',
dataScope: '',
provider: 'provider',
options: [],
value: ''
});
});
afterEach(function () {
$.ajax = originaljQueryAjax;
});
describe('"validateInitialValue" method', function () {
it('Should be defined', function () {
expect(obj.hasOwnProperty('validateInitialValue')).toBeDefined();
});
it('Should call not call ajax if value is empty', function () {
$.ajax = jasmine.createSpy();
spyOn(obj, 'validationLoading');
spyOn(obj, 'value').and.returnValue('');
expect(obj.validateInitialValue()).toBeUndefined();
expect($.ajax).not.toHaveBeenCalled();
expect(obj.validationLoading).toHaveBeenCalledWith(false);
});
it('Should call ajax if value is not empty', function () {
var successCallback,
completeCallback,
responseData = {
label: 'hello world',
value: 'hello world'
};
$.ajax = jasmine.createSpy().and.callFake(function (request) {
successCallback = request.success.bind(obj);
completeCallback = request.complete.bind(obj);
});
spyOn(obj, 'validationLoading');
spyOn(obj, 'value').and.returnValue('hello world');
spyOn(obj, 'options');
spyOn(obj, 'setCaption');
expect(obj.validateInitialValue()).toBeUndefined();
successCallback(responseData);
completeCallback();
expect($.ajax).toHaveBeenCalled();
expect(obj.validationLoading).toHaveBeenCalledWith(false);
expect(obj.loadedOption).toBe(responseData);
expect(obj.options).toHaveBeenCalledWith([responseData]);
expect(obj.setCaption).toHaveBeenCalled();
});
});
});
});
@@ -0,0 +1,40 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(['Magento_Catalog/js/components/disable-on-option/yesno'], function (YesNo) {
'use strict';
var model;
describe('Magento_Catalog/js/components/disable-on-option/yesno', function () {
beforeEach(function () {
model = new YesNo({
name: 'dynamic_rows',
dataScope: '',
value: 12,
visible: true,
disabled: false
});
});
it('Verify initial value', function () {
expect(model.get('value')).toBe(12);
});
it('Verify value when element becomes invisible', function () {
model.set('visible', false);
expect(model.get('value')).toBe(0);
});
it('Verify value when element becomes disabled', function () {
model.set('disabled', false);
expect(model.get('value')).toBe(12);
});
it('Verify value when element becomes invisable and disabled', function () {
model.set('disabled', true);
model.set('visible', false);
expect(model.get('value')).toBe(0);
});
});
});
@@ -0,0 +1,132 @@
/*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint-disable max-nested-callbacks*/
/*jscs:disable jsDoc*/
define([
'jquery',
'Magento_Catalog/js/product-gallery'
], function ($) {
'use strict';
var galleryEl,
defaultConfig = {
images: [
{
disabled: 0,
file: '/e/a/earth.jpg',
position: 2,
url: 'http://localhost/media/catalog/product/e/a/earth.jpg',
size: 2048,
'value_id': 2
},
{
disabled: 0,
file: '/m/a/mars.jpg',
position: 3,
url: 'http://localhost/media/catalog/product/m/a/mars.jpg',
size: 3072,
'value_id': 3
},
{
disabled: 0,
file: '/j/u/jupiter.jpg',
position: 5,
size: 5120,
url: 'http://localhost/media/catalog/product/j/u/jupiter.jpg',
'value_id': 5
}
],
types: {
'image': {
code: 'image',
label: 'Base',
name: 'product[image]'
},
'small_image': {
code: 'small_image',
label: 'Small',
name: 'product[image]'
},
'thumbnail': {
code: 'thumbnail',
label: 'Thumbnail',
name: 'product[image]'
}
}
};
function init(config) {
$(galleryEl).productGallery($.extend({}, defaultConfig, config || {}));
}
beforeEach(function () {
$('<form>' +
'<div id="media_gallery_content" class="gallery">' +
'<script id="media_gallery_content-template" data-template="image" type="text/x-magento-template">' +
'<div class="image item <% if(data.disabled == 1){ %>hidden-for-front<% } %>" data-role="image">' +
'<input type="hidden" name="product[media_gallery][images][<%- data.file_id %>][position]"' +
' value="<%- data.position %>" data-form-part="product_form" class="position"/>' +
'<input type="hidden" name="product[media_gallery][images][<%- data.file_id %>][file]"' +
' value="<%- data.file %>" data-form-part="product_form"/>' +
'<input type="hidden" name="product[media_gallery][images][<%- data.file_id %>][label]"' +
' value="<%- data.label %>" data-form-part="product_form"/>' +
'<div class="product-image-wrapper">' +
'<img class="product-image" data-role="image-element" src="<%- data.url %>" alt=""/>' +
'<div class="actions"></div>' +
'</div>' +
'</div>' +
'</script>' +
'</div>' +
'</form>'
).appendTo(document.body);
galleryEl = document.getElementById('media_gallery_content');
});
afterEach(function () {
$(galleryEl).remove();
galleryEl = undefined;
});
describe('Magento_Catalog/js/product-gallery', function () {
describe('_create()', function () {
it('check that existing images are rendered correctly', function () {
init();
expect($(galleryEl).find('[data-role=image]').length).toBe(3);
expect($(galleryEl).find('[data-role=image]:nth-child(1) .position').val()).toBe('2');
expect($(galleryEl).find('[data-role=image]:nth-child(2) .position').val()).toBe('3');
expect($(galleryEl).find('[data-role=image]:nth-child(3) .position').val()).toBe('5');
});
});
describe('_addItem()', function () {
it('check that new image is inserted at the first position if there were no existing images', function () {
init({
images: []
});
$(galleryEl).trigger('addItem', {
file: '/s/a/saturn.jpg.tmp',
name: 'saturn.jpg',
size: 1024,
type: 'image/jpeg',
url: 'http://localhost/media/tmp/catalog/product/s/a/saturn.jpg'
});
expect($(galleryEl).find('[data-role=image]').length).toBe(1);
expect($(galleryEl).find('[data-role=image]:nth-child(1) .position').val()).toBe('1');
});
it('check that new image is inserted at the last position if there were existing images', function () {
init();
$(galleryEl).trigger('addItem', {
file: '/s/a/saturn.jpg.tmp',
name: 'saturn.jpg',
size: 1024,
type: 'image/jpeg',
url: 'http://localhost/media/tmp/catalog/product/s/a/saturn.jpg'
});
expect($(galleryEl).find('[data-role=image]').length).toBe(4);
// check that new image position is the position of previous image in the list plus one
expect($(galleryEl).find('[data-role=image]:nth-child(4) .position').val()).toBe('6');
});
});
});
});
@@ -0,0 +1,141 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define([
'underscore',
'Magento_Catalog/js/components/use-parent-settings/select',
'Magento_Catalog/js/components/use-parent-settings/toggle-disabled-mixin'
], function (_, select, mixin) {
'use strict';
var CustomInput = mixin(select),
defaultProperties = {
name: 'uiSelect',
dataScope: '',
provider: 'provider',
service: true
},
obj;
describe('toggle-disabled-mixin structure tests', function () {
var defaultContext = require.s.contexts._;
obj = new CustomInput(defaultProperties);
it('mixin is present in RequireJs config', function () {
var requireJsConfig = defaultContext.config
.config.mixins['Magento_Catalog/js/components/use-parent-settings/select'];
expect(
requireJsConfig['Magento_Catalog/js/components/use-parent-settings/toggle-disabled-mixin']
).toBe(true);
});
it('Check for useParent property', function () {
expect(obj.hasOwnProperty('useParent')).toBeTruthy();
expect(typeof obj.useParent).toEqual('boolean');
expect(obj.useParent).toEqual(false);
});
it('Check for useDefaults property', function () {
expect(obj.hasOwnProperty('useDefaults')).toBeTruthy();
expect(typeof obj.useDefaults).toEqual('boolean');
expect(obj.useDefaults).toEqual(false);
});
it('Check for toggleDisabled method', function () {
expect(obj.toggleDisabled).toBeDefined();
expect(typeof obj.toggleDisabled).toEqual('function');
});
it('Check for saveUseDefaults method', function () {
expect(obj.saveUseDefaults).toBeDefined();
expect(typeof obj.saveUseDefaults).toEqual('function');
});
it('Check for setInitialValue method', function () {
expect(obj.setInitialValue).toBeDefined();
expect(typeof obj.setInitialValue).toEqual('function');
});
it('Check for toggleUseDefault method', function () {
expect(obj.toggleUseDefault).toBeDefined();
expect(typeof obj.toggleUseDefault).toEqual('function');
});
});
describe('toggle-disabled-mixin functionality', function () {
var dataProvider = [
{
defaults: {
useParent: false,
useDefaults: false
},
expected: {
disabled: false
}
},
{
defaults: {
useParent: true,
useDefaults: false
},
expected: {
disabled: true
}
},
{
defaults: {
useParent: false,
useDefaults: true
},
expected: {
disabled: true
}
},
{
defaults: {
useParent: true,
useDefaults: true
},
expected: {
disabled: true
}
}
];
dataProvider.forEach(function (state) {
describe(JSON.stringify(state.defaults), function () {
beforeEach(function () {
obj = new CustomInput(
_.extend(defaultProperties, state.defaults)
);
});
it('Check disabled state', function () {
expect(obj.disabled()).toEqual(state.expected.disabled);
});
it('Check checked state', function () {
expect(obj.isUseDefault()).toEqual(state.defaults.useDefaults);
});
it('Check of using parent settings', function () {
obj.toggleDisabled(true);
expect(obj.isUseDefault()).toEqual(state.defaults.useDefaults);
expect(obj.disabled()).toEqual(true);
});
it('Check of using self settings', function () {
obj.toggleDisabled(false);
expect(obj.isUseDefault()).toEqual(state.defaults.useDefaults);
expect(obj.disabled()).toEqual(obj.isUseDefault());
});
});
});
});
});
@@ -0,0 +1,67 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(['Magento_Catalog/js/utils/percentage-price-calculator'], function (percentagePriceCalculator) {
'use strict';
var basePrice = 100,
negativeBasePrice = -10,
decimalBasePrice = '100,1',
zeroBasePrice = 0;
describe('Check valid calculation', function () {
it('5%', function () {
expect(percentagePriceCalculator(basePrice, '5%')).toBe('95.00');
});
it('0%', function () {
expect(percentagePriceCalculator(basePrice, '0%')).toBe('100.00');
});
it('100%', function () {
expect(percentagePriceCalculator(basePrice, '100%')).toBe('0.00');
});
it('110%', function () {
expect(percentagePriceCalculator(basePrice, '110%')).toBe('0.00');
});
it('5.5%', function () {
expect(percentagePriceCalculator(basePrice, '5.5%')).toBe('94.50');
});
it('.5%', function () {
expect(percentagePriceCalculator(basePrice, '.5%')).toBe('99.50');
});
it('-7%', function () {
expect(percentagePriceCalculator(basePrice, '-7%')).toBe('107.00');
});
});
describe('Check invalid input calculation', function () {
it('invalid with %', function () {
expect(percentagePriceCalculator(basePrice, '7p%')).toBe('');
expect(percentagePriceCalculator(basePrice, '-%')).toBe('');
});
it('without %', function () {
expect(percentagePriceCalculator(basePrice, '7p')).toBe('7p');
expect(percentagePriceCalculator(basePrice, '0')).toBe('0');
expect(percentagePriceCalculator(basePrice, 'qwe')).toBe('qwe');
});
it('just %', function () {
expect(percentagePriceCalculator(basePrice, '%')).toBe('');
});
it('empty', function () {
expect(percentagePriceCalculator(basePrice, '')).toBe('');
});
});
describe('Other', function () {
it('negative base price', function () {
expect(percentagePriceCalculator(negativeBasePrice, '10%')).toBe('-9.00');
});
it('decimal base price', function () {
expect(percentagePriceCalculator(decimalBasePrice, '10%')).toBe('90.09');
});
it('zero base price', function () {
expect(percentagePriceCalculator(zeroBasePrice, '10%')).toBe('0.00');
});
});
});
@@ -0,0 +1,362 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire'
], function ($, Squire) {
'use strict';
var injector = new Squire(),
mocks = {},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/list/columns/final-price'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: '',
links: '',
listens: ''
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/product/list/columns/final-price', function () {
describe('"getPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'final_price': price
}
}
};
expect(obj.getPrice(row)).toBe(price);
});
});
describe('"getRegularPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'regular_price': price
}
}
};
expect(obj.getRegularPrice(row)).toBe(price);
});
});
describe('"hasPriceRange" method', function () {
it('Check returned value with equal mix_regular_price and max_regular_price', function () {
var price = 100,
row = {
'price_info': {
'max_regular_price': price,
'min_regular_price': price
}
};
expect(obj.hasPriceRange(row)).toBe(false);
});
it('Check returned value with different mix_regular_price and max_regular_price', function () {
var row = {
'price_info': {
'max_regular_price': 100,
'min_regular_price': 200
}
};
expect(obj.hasPriceRange(row)).toBe(true);
});
});
describe('"hasSpecialPrice" method', function () {
it('Check returned value with regular_price that is more than final_price', function () {
var row = {
'price_info': {
'regular_price': 200,
'final_price': 100
}
};
expect(obj.hasSpecialPrice(row)).toBe(true);
});
it('Check returned value with regular_price that is less than final_price', function () {
var row = {
'price_info': {
'max_regular_price': 200,
'min_regular_price': 100
}
};
expect(obj.hasSpecialPrice(row)).toBe(false);
});
});
describe('"isMinimalPrice" method', function () {
it('Check returned value with minimal_price that is more than final_price', function () {
var row = {
'price_info': {
'minimal_price': 200,
'final_price': 100
}
};
expect(obj.isMinimalPrice(row)).toBe(false);
});
it('Check returned value with minimal_price that is less than final_price', function () {
var row = {
'price_info': {
'minimal_price': 100,
'final_price': 200
}
};
expect(obj.isMinimalPrice(row)).toBe(true);
});
});
describe('"getMinimalPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'minimal_price': price
}
}
};
expect(obj.getMinimalPrice(row)).toBe(price);
});
});
describe('"isSalable" method', function () {
it('Check returned value', function () {
var salable = true,
row = {
'is_salable': salable
};
expect(obj.isSalable(row)).toBe(salable);
});
});
describe('"getMaxPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'max_price': price
}
}
};
expect(obj.getMaxPrice(row)).toBe(price);
});
});
describe('"getMaxRegularPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'max_regular_price': price
}
}
};
expect(obj.getMaxRegularPrice(row)).toBe(price);
});
});
describe('"getMinRegularPrice" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'min_regular_price': price
}
}
};
expect(obj.getMinRegularPrice(row)).toBe(price);
});
});
describe('"getAdjustmentCssClasses" method', function () {
var price = 100,
row = {
'price_info': {
'formatted_prices': {
'min_regular_price': price
}
}
};
beforeEach(function () {
obj.getAdjustments = jasmine.createSpy().and.returnValue([{
index: 1
}]);
});
it('Check returned value', function () {
expect(obj.getAdjustmentCssClasses(row)).toBe('1');
});
it('Check calls "getAdjustments" method', function () {
obj.getAdjustmentCssClasses(row);
expect(obj.getAdjustments).toHaveBeenCalled();
});
});
describe('"getMinimalPriceAmount" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'minimal_price': price
}
};
expect(obj.getMinimalPriceAmount(row)).toBe(price);
});
});
describe('"getMinimalRegularPriceAmount" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'min_regular_price': price
}
};
expect(obj.getMinimalRegularPriceAmount(row)).toBe(price);
});
});
describe('"getMaximumPriceAmount" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'max_price': price
}
};
expect(obj.getMaximumPriceAmount(row)).toBe(price);
});
});
describe('"getMaximumRegularPriceAmount" method', function () {
it('Check returned value', function () {
var price = 100,
row = {
'price_info': {
'max_regular_price': price
}
};
expect(obj.getMaximumRegularPriceAmount(row)).toBe(price);
});
});
describe('"showMinRegularPrice" method', function () {
it('Check call "getMinimalPriceAmount" and "getMinimalRegularPriceAmount" methods', function () {
var row = {};
obj.getMinimalPriceAmount = jasmine.createSpy();
obj.getMinimalRegularPriceAmount = jasmine.createSpy();
obj.showMinRegularPrice(row);
expect(obj.getMinimalPriceAmount).toHaveBeenCalledWith(row);
expect(obj.getMinimalRegularPriceAmount).toHaveBeenCalledWith(row);
});
it('Check returned value when minimal price amount is less than regular price amount', function () {
obj.getMinimalPriceAmount = jasmine.createSpy().and.returnValue(1);
obj.getMinimalRegularPriceAmount = jasmine.createSpy().and.returnValue(2);
expect(obj.showMinRegularPrice()).toBe(true);
});
it('Check returned value when minimal price amount is more than regular price amount', function () {
obj.getMinimalPriceAmount = jasmine.createSpy().and.returnValue(2);
obj.getMinimalRegularPriceAmount = jasmine.createSpy().and.returnValue(1);
expect(obj.showMinRegularPrice()).toBe(false);
});
});
describe('"showMaxRegularPrice" method', function () {
it('Check call "getMaximumPriceAmount" and "getMaximumRegularPriceAmount" methods', function () {
var row = {};
obj.getMaximumPriceAmount = jasmine.createSpy();
obj.getMaximumRegularPriceAmount = jasmine.createSpy();
obj.showMaxRegularPrice(row);
expect(obj.getMaximumPriceAmount).toHaveBeenCalledWith(row);
expect(obj.getMaximumRegularPriceAmount).toHaveBeenCalledWith(row);
});
it('Check returned value when maximal price amount is less than regular price amount', function () {
obj.getMaximumPriceAmount = jasmine.createSpy().and.returnValue(1);
obj.getMaximumRegularPriceAmount = jasmine.createSpy().and.returnValue(2);
expect(obj.showMaxRegularPrice()).toBe(true);
});
it('Check returned value when maximal price amount is more than regular price amount', function () {
obj.getMaximumPriceAmount = jasmine.createSpy().and.returnValue(2);
obj.getMaximumRegularPriceAmount = jasmine.createSpy().and.returnValue(1);
expect(obj.showMaxRegularPrice()).toBe(false);
});
});
describe('"getBody" method', function () {
it('Check returned value', function () {
var result = 'template';
obj.bodyTmpl = result;
expect(obj.getBody()).toBe(result);
});
});
describe('"getAdjustments" method', function () {
var adjustment = {
setPriceType: jasmine.createSpy()
};
beforeEach(function () {
obj.elems = jasmine.createSpy().and.returnValue([
adjustment
]);
});
it('Check call elems property', function () {
obj.getAdjustments();
expect(obj.elems).toHaveBeenCalled();
});
it('Check call "setPriceType" value', function () {
var arg = 'type';
obj.priceType = arg;
obj.getAdjustments();
expect(adjustment.setPriceType).toHaveBeenCalledWith(arg);
});
it('Check returned value', function () {
var source = {};
obj.source = source;
expect(obj.getAdjustments()[0].source).toBe(source);
});
});
});
});
@@ -0,0 +1,112 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire'
], function ($, Squire) {
'use strict';
var injector = new Squire(),
mocks = {},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/list/columns/image', 'knockoutjs/knockout-es5'],
function (Constr) {
obj = new Constr({
sortable: true,
sorting: false,
headerTmpl: 'header',
bodyTmpl: 'body',
/** Stub */
source: function () {
return {
column: {
image: 'image'
}
};
}
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/product/list/columns/image', function () {
var image = {
url: 'url',
width: 100,
height: 100,
'resized_width': 200
},
code = 'code',
row = {
images: [
{
label: 'first',
code: code
},
{
label: 'second',
code: code
}
]
};
beforeEach(function () {
obj.source = jasmine.createSpy().and.returnValue({
column: {
image: {
imageCode: 'code'
}
}
});
});
describe('"getImages" method', function () {
it('Check returned value', function () {
obj.imageCode = code;
expect(obj.getImage(row.images)).toBe(row.images[1]);
});
});
describe('"getImageUrl" method', function () {
it('Check call "getImage" method', function () {
obj.getImage = jasmine.createSpy().and.returnValue(image);
obj.getImageUrl(row);
expect(obj.getImage).toHaveBeenCalledWith(row.images);
});
});
describe('"getWidth" method', function () {
it('Check call "getImage" method', function () {
obj.getImage = jasmine.createSpy().and.returnValue(image);
obj.getImageUrl(row);
expect(obj.getImage).toHaveBeenCalledWith(row.images);
});
});
describe('"getHeight" method', function () {
it('Check call "getImage" method', function () {
obj.getImage = jasmine.createSpy().and.returnValue(image);
obj.getImageUrl(row);
expect(obj.getImage).toHaveBeenCalledWith(row.images);
});
});
describe('"getResizedImageWidth" method', function () {
it('Check call "getImage" method', function () {
obj.getImage = jasmine.createSpy().and.returnValue(image);
obj.getImageUrl(row);
expect(obj.getImage).toHaveBeenCalledWith(row.images);
});
});
});
});
@@ -0,0 +1,276 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire',
'jquery'
], function (Squire, $) {
'use strict';
var injector = new Squire(),
widget,
menuContainer,
mocks = {
'Magento_Theme/js/model/breadcrumb-list': jasmine.createSpyObj(['push'])
},
defaultContext = require.s.contexts._,
menuItem = $(
'<li class="level0 category-item">' +
'<a href="http://localhost.com/cat1.html">Cat1</a>' +
'</li>'
)[0],
/**
* Create context object.
*
* @param {Object} prototype
* @param {*} options
* @return {Object}
*/
createContext = function (prototype, options) {
options = options || {};
return $.extend(Object.create(prototype), options);
};
beforeAll(function (done) {
injector.mock(mocks);
injector.require(
[
'Magento_Catalog/js/product/breadcrumbs',
'Magento_Theme/js/view/breadcrumbs'
], function (mixin, breadcrumb) {
widget = mixin(breadcrumb);
done();
}
);
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/product/breadcrumbs', function () {
it('mixin is applied to Magento_Theme/js/view/breadcrumbs', function () {
var breadcrumbMixins = defaultContext.config.config.mixins['Magento_Theme/js/view/breadcrumbs'];
expect(breadcrumbMixins['Magento_Catalog/js/product/breadcrumbs']).toBe(true);
});
describe('Check Magento_Catalog/js/product/breadcrumbs methods', function () {
beforeEach(function () {
menuContainer = $('<nav data-action="navigation"><ul></ul></nav>');
$('body').append(menuContainer);
});
afterEach(function () {
menuContainer.remove();
});
it('Check _appendCatalogCrumbs call', function () {
var categoryCrumb = {
'name': 'category100',
'link': window.location.href,
'title': 'Test'
},
context = {
options: {
product: 'simple'
}
},
appendCatalogCrumbsHandler;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._appendCatalogCrumbs).toBeDefined();
$('[data-action="navigation"] > ul').html(menuItem);
spyOn(widget.prototype, '_resolveCategoryCrumbs').and.returnValues([], [categoryCrumb]);
spyOn(widget.prototype, '_getProductCrumb');
spyOn(widget.prototype.options, 'product').and.returnValue('simple');
context = createContext(widget.prototype, context);
appendCatalogCrumbsHandler = widget.prototype._appendCatalogCrumbs.bind(context);
appendCatalogCrumbsHandler();
expect(widget.prototype._resolveCategoryCrumbs).toHaveBeenCalled();
expect(mocks['Magento_Theme/js/model/breadcrumb-list'].push).toHaveBeenCalled();
expect(mocks['Magento_Theme/js/model/breadcrumb-list'].push.calls.count()).toBe(1);
mocks['Magento_Theme/js/model/breadcrumb-list'].push.calls.reset();
appendCatalogCrumbsHandler();
expect(widget.prototype._resolveCategoryCrumbs).toHaveBeenCalled();
expect(mocks['Magento_Theme/js/model/breadcrumb-list'].push).toHaveBeenCalledWith(categoryCrumb);
expect(mocks['Magento_Theme/js/model/breadcrumb-list'].push.calls.count()).toBe(2);
});
it('Check _getCategoryCrumb call', function () {
var item = $('<a href="http://localhost.com/cat1.html">Cat1</a>');
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._getCategoryCrumb).toBeDefined();
expect(widget.prototype._getCategoryCrumb(item)).toEqual(jasmine.objectContaining(
{
'name': 'category',
'label': 'Cat1',
'link': 'http://localhost.com/cat1.html'
}
));
});
it('Check _getProductCrumb call', function () {
var context = {
options: {
product: 'simple'
}
},
getProductCrumbHandler;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._getProductCrumb).toBeDefined();
getProductCrumbHandler = widget.prototype._getProductCrumb.bind(context);
expect(getProductCrumbHandler()).toEqual(jasmine.objectContaining(
{
'name': 'product',
'label': 'simple'
}
));
});
it('Check _resolveCategoryMenuItem call with empty navigation menu', function () {
var resolveCategoryMenuHandler,
context;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._resolveCategoryMenuItem).toBeDefined();
context = createContext(widget.prototype);
resolveCategoryMenuHandler = widget.prototype._resolveCategoryMenuItem.bind(context);
spyOn(widget.prototype, '_resolveCategoryUrl').and.returnValue('');
expect(resolveCategoryMenuHandler()).toBeNull();
});
it('Check _resolveCategoryMenuItem call with non-empty navigation menu', function () {
var result,
context,
resolveCategoryMenuHandler;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._resolveCategoryMenuItem).toBeDefined();
$('[data-action="navigation"] > ul').html(menuItem);
spyOn(widget.prototype, '_resolveCategoryUrl').and.returnValue('http://localhost.com/cat1.html');
context = createContext(widget.prototype);
resolveCategoryMenuHandler = widget.prototype._resolveCategoryMenuItem.bind(context);
result = resolveCategoryMenuHandler();
expect(result).not.toBeNull();
expect(result.length).toBe(1);
expect(result[0].tagName.toLowerCase()).toEqual('a');
expect(result[0].href).toEqual('http://localhost.com/cat1.html');
});
it('Check _resolveCategoryCrumbs call with empty navigation menu', function () {
var result,
context,
resolveCategoryCrumbsHandler;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._resolveCategoryCrumbs).toBeDefined();
spyOn(widget.prototype, '_resolveCategoryUrl').and.returnValue('');
context = createContext(widget.prototype);
resolveCategoryCrumbsHandler = widget.prototype._resolveCategoryCrumbs.bind(context);
result = resolveCategoryCrumbsHandler();
expect(result).toEqual(jasmine.any(Array));
expect(result).toEqual([]);
});
it('Check _resolveCategoryCrumbs call with non-empty navigation menu', function () {
var result,
context,
resolveCategoryCrumbsHandler;
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._resolveCategoryCrumbs).toBeDefined();
$('[data-action="navigation"] > ul').html(menuItem);
spyOn(widget.prototype, '_resolveCategoryUrl').and.returnValue('http://localhost.com/cat1.html');
context = createContext(widget.prototype);
resolveCategoryCrumbsHandler = widget.prototype._resolveCategoryCrumbs.bind(context);
result = resolveCategoryCrumbsHandler();
expect(result).not.toBeNull();
expect(result).toEqual(jasmine.any(Array));
expect(result.length).toBe(1);
expect(result[0]).toEqual(jasmine.objectContaining(
{
'name': 'category',
'label': 'Cat1',
'link': 'http://localhost.com/cat1.html'
}
));
});
it('Check _getParentMenuItem call', function () {
var result,
menuItems = $(
'<li class="level0 nav-1">' +
'<a href="http://localhost.com/cat1.html">cat1</a>' +
'<ul>' +
'<li class="level1 nav-1-1">' +
'<a href="http://localhost.com/cat1/cat21.html">cat21</a>' +
'</li>' +
'</ul>' +
'</li>'
),
context,
getParentMenuHandler;
$('[data-action="navigation"] > ul').html(menuItems);
expect(widget).toBeDefined();
expect(widget).toEqual(jasmine.any(Function));
expect(widget.prototype._getParentMenuItem).toBeDefined();
context = createContext(widget.prototype);
getParentMenuHandler = widget.prototype._getParentMenuItem.bind(context);
result = getParentMenuHandler($('[href="http://localhost.com/cat1/cat21.html"]'));
expect(result).toBeDefined();
expect(result.length).toBe(1);
expect(result[0].tagName.toLowerCase()).toEqual('a');
expect(result.attr('href')).toEqual('http://localhost.com/cat1.html');
result = getParentMenuHandler($('[href="http://localhost.com/cat1.html"]'));
expect(result).toBeNull();
});
});
});
});
@@ -0,0 +1,47 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'Magento_Catalog/js/product/list/toolbar'
], function ($) {
'use strict';
describe('Magento_Catalog/js/product/list/toolbar', function () {
var widget,
toolbar;
beforeEach(function () {
toolbar = $('<div class="toolbar"></div>');
});
afterEach(function () {
toolbar.remove();
});
it('Widget extends jQuery object', function () {
expect($.mage.productListToolbarForm).toBeDefined();
});
it('Toolbar is initialized', function () {
spyOn($.mage.productListToolbarForm.prototype, '_create');
toolbar.productListToolbarForm();
expect($.mage.productListToolbarForm.prototype._create).toEqual(jasmine.any(Function));
expect($.mage.productListToolbarForm.prototype._create).toHaveBeenCalledTimes(1);
});
it('Toolbar receives options properly', function () {
toolbar.productListToolbarForm();
expect(toolbar.productListToolbarForm('option', 'page')).toBe('p');
});
it('Toolbar receives element properly', function () {
widget = toolbar.productListToolbarForm();
expect(widget).toBe(toolbar);
});
});
});
@@ -0,0 +1,202 @@
/**
* Copyright 2023 Adobe
* All Rights Reserved.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire',
'underscore'
], function (Squire, _) {
'use strict';
var injector = new Squire(),
obj,
customerDataIds,
localStorageIds,
timestamp,
namespace = 'namespace',
windowCheckoutData = window.checkout,
customerDataGet = function () {
return {
items: customerDataIds
};
},
customerData = {
get: jasmine.createSpy().and.returnValue(customerDataGet)
},
productResolverIds = [],
productResolver = jasmine.createSpy().and.callFake(function () {
return productResolverIds;
}),
storage = {
onStorageInit: jasmine.createSpy(),
createStorage: jasmine.createSpy()
},
mocks = {
'Magento_Customer/js/customer-data': customerData,
'Magento_Catalog/js/product/view/product-ids-resolver': productResolver,
'Magento_Catalog/js/product/storage/storage-service': storage
};
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/provider'], function (UiClass) {
timestamp = new Date().getTime() / 1000;
obj = new UiClass({
identifiersConfig: {
namespace: namespace
},
ids: {
'website-1-1': {
added_at: timestamp - 300,
product_id: 1,
scope_id: 1
}
},
data: {
store: '1',
currency: 'USD',
productCurrentScope: 'website'
}
});
localStorageIds = {
'website-1-2': {
added_at: timestamp - 60,
product_id: 2,
scope_id: 1
},
'website-1-3': {
added_at: timestamp - 180,
product_id: 3,
scope_id: 1
}
};
customerDataIds = {
4: {
added_at: timestamp - 360,
product_id: 4,
scope_id: 1
}
};
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {
}
window.localStorage.clear();
window.checkout = windowCheckoutData;
});
describe('Magento_Catalog/js/product/provider', function () {
describe('"_resolveDataByIds" method', function () {
beforeEach(function () {
obj.initIdsListener = jasmine.createSpy();
obj.idsMerger = jasmine.createSpy();
obj.idsHandler = jasmine.createSpy();
obj.filterIds = jasmine.createSpy().and.returnValue({});
});
it('check "window.checkout" is required', function () {
window.checkout = undefined;
obj.ids = jasmine.createSpy();
obj._resolveDataByIds();
expect(obj.ids).not.toHaveBeenCalled();
expect(obj.filterIds).not.toHaveBeenCalled();
expect(obj.idsHandler).not.toHaveBeenCalled();
expect(obj.initIdsListener).not.toHaveBeenCalled();
expect(obj.idsMerger).not.toHaveBeenCalled();
});
it('check that initial ids, localstorage ids and ids from customer data are processed', function () {
var initialIds = obj.ids();
window.checkout = {
baseUrl: 'http://localhost/',
websiteId: 1
};
obj.idsStorage = {
get: jasmine.createSpy().and.returnValue(localStorageIds),
lifetime: 1000
};
obj.prepareDataFromCustomerData = jasmine.createSpy().and.returnValue(customerDataIds);
customerData.get = jasmine.createSpy().and.returnValue(customerDataGet);
obj._resolveDataByIds();
expect(obj.filterIds).toHaveBeenCalledOnceWith(initialIds);
expect(obj.idsHandler).toHaveBeenCalledOnceWith({});
expect(obj.initIdsListener).toHaveBeenCalled();
expect(customerData.get).toHaveBeenCalledOnceWith(namespace);
expect(obj.prepareDataFromCustomerData).toHaveBeenCalledOnceWith({items: customerDataIds});
expect(obj.idsMerger).toHaveBeenCalledOnceWith(localStorageIds, customerDataIds);
});
});
describe('"idsMerger" method', function () {
beforeEach(function () {
obj.idsHandler = jasmine.createSpy();
obj.filterIds = jasmine.createSpy().and.returnValue({});
});
it('check merge empty', function () {
obj.idsMerger({}, {});
expect(obj.filterIds).not.toHaveBeenCalled();
expect(obj.idsHandler).not.toHaveBeenCalled();
});
it('check merge not empty', function () {
var initialIds = obj.ids();
obj.idsMerger(localStorageIds, {});
expect(obj.filterIds).toHaveBeenCalledOnceWith(_.extend({}, initialIds, localStorageIds));
expect(obj.idsHandler).toHaveBeenCalledOnceWith({});
});
});
describe('"prepareDataFromCustomerData" method', function () {
it('argument is empty', function () {
expect(obj.prepareDataFromCustomerData({})).toEqual({});
});
it('argument is an object and has "items" property', function () {
expect(obj.prepareDataFromCustomerData({items: customerDataIds})).toEqual(customerDataIds);
});
it('argument is an object and does not have "items" property', function () {
expect(obj.prepareDataFromCustomerData(customerDataIds)).toEqual(customerDataIds);
});
});
describe('"filterIds" method', function () {
beforeEach(function () {
window.checkout = {
websiteId: 1
};
obj.idsStorage = {
lifetime: 1000
};
});
it('filters out "out of scope" ids', function () {
window.checkout.websiteId = 2;
expect(obj.filterIds(localStorageIds)).toEqual({});
});
it('filters out expired ids', function () {
obj.idsStorage.lifetime = 100;
expect(obj.filterIds(localStorageIds)).toEqual({2: localStorageIds['website-1-2']});
});
it('filters out current product id', function () {
productResolverIds.push(2);
expect(obj.filterIds(localStorageIds)).toEqual({3: localStorageIds['website-1-3']});
});
});
});
});
@@ -0,0 +1,84 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'Magento_Catalog/js/product/remaining-characters',
'jquery'
], function (remainingCharacters, $) {
'use strict';
describe('Magento_Catalog/js/product/remaining-characters', function () {
var widget,
note;
beforeEach(function () {
widget = $('<input type="text" data-selector="options[1]"/>');
note = $('<p class="note note_1"><span class="character-counter"></span></p>');
$('body').append(widget).append(note);
widget.remainingCharacters({
maxLength: '10',
noteSelector: '.note_1',
counterSelector: '.note_1 .character-counter'
});
});
afterEach(function () {
widget.remove();
note.remove();
});
describe('Note text is updated on input change', function () {
it('check empty input', function () {
var testData = {
input: '',
action: 'change',
expectedText: '(10 remaining)'
};
widget.val(testData.input);
widget.trigger(testData.action);
expect(note.find('.character-counter').text()).toBe(testData.expectedText);
});
it('check input length less than character limit', function () {
var testData = {
input: 'abc',
action: 'change',
expectedText: '(7 remaining)'
};
widget.val(testData.input);
widget.trigger(testData.action);
expect(note.find('.character-counter').text()).toBe(testData.expectedText);
});
it('check input length equals character limit', function () {
var testData = {
input: 'abcdefghij',
action: 'paste',
expectedText: '(0 remaining)'
};
widget.val(testData.input);
widget.trigger(testData.action);
expect(note.find('.character-counter').text()).toBe(testData.expectedText);
});
it('check input length greater than character limit', function () {
var testData = {
input: 'abcdefghijkl',
action: 'change',
expectedText: '(2 too many)'
};
widget.val(testData.input);
widget.trigger(testData.action);
expect(note.find('.character-counter').text()).toBe(testData.expectedText);
});
});
});
});
@@ -0,0 +1,425 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire',
'underscore'
], function ($, Squire, _) {
'use strict';
var injector = new Squire(),
/**
* Mock for customerData get method
*/
customerDataGet = function () {
return {
customerDataGet: 'customerDataGetValue'
};
},
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy().and.returnValue(customerDataGet)
},
'Magento_Catalog/js/product/query-builder': {
buildQuery: jasmine.createSpy().and.returnValue({})
}
},
obj;
/**
* Mock for customerData subscribe method
*/
customerDataGet.subscribe = jasmine.createSpy();
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/storage/data-storage'], function (instance) {
obj = _.extend({}, instance);
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
window.localStorage.clear();
});
describe('Magento_Catalog/js/product/storage/data-storage', function () {
describe('"initCustomerDataInvalidateListener" method', function () {
it('check returned value', function () {
expect(obj.initCustomerDataReloadListener()).toBe(obj);
});
});
describe('"initDataListener" method', function () {
it('check calls "subscribe"', function () {
obj.data = {
subscribe: jasmine.createSpy()
};
obj.initDataListener();
expect(obj.data.subscribe).toHaveBeenCalled();
});
});
describe('"initProvideStorage" method', function () {
beforeEach(function () {
obj.providerHandler = jasmine.createSpy();
});
it('check calls "providerHandler" method', function () {
obj.initProvideStorage();
expect(obj.providerHandler).toHaveBeenCalledWith(customerDataGet());
});
it('check returned value', function () {
expect(obj.initProvideStorage()).toBe(obj);
});
});
describe('"dataHandler" method', function () {
beforeEach(function () {
obj.localStorage = {
removeAll: jasmine.createSpy(),
set: jasmine.createSpy()
};
});
afterEach(function () {
window.localStorage.clear();
});
it('check calls "dataHandler" method with data', function () {
var data = {
property: 'value'
};
obj.dataHandler(data);
expect(window.localStorage.getItem(obj.namespace)).toBe(JSON.stringify(data));
});
it('check calls "dataHandler" method with empty data', function () {
obj.dataHandler({});
expect(obj.localStorage.removeAll).toHaveBeenCalled();
});
});
describe('"providerHandler" method', function () {
beforeEach(function () {
obj.localStorage = {
removeAll: jasmine.createSpy(),
set: jasmine.createSpy()
};
/**
* Mock for observable data property
*/
obj.data = function (data) {
if (!data) {
return {
existingKey1: 'existingKey1Value',
existingKey2: 'existingKey2Value'
};
}
this.result = data;
};
});
it('check calls "providerHandler" method with data', function () {
var data = {
items: {
newKey: 'newKeyValue',
existingKey2: 'existingKey2NewValue'
}
};
obj.providerHandler(data);
expect(obj.result.existingKey1).toBe('existingKey1Value');
expect(obj.result.existingKey2).toBe('existingKey2NewValue');
expect(obj.result.newKey).toBe('newKeyValue');
});
it('check calls "providerHandler" method without data', function () {
obj.providerHandler({});
expect(obj.result).toBe(undefined);
});
});
describe('"setIds" method', function () {
var currency = 'currency',
store = '1',
ids = '4';
beforeEach(function () {
obj.data = {
valueHasMutated: jasmine.createSpy()
};
obj.loadDataFromServer = jasmine.createSpy();
});
it('check calls "setIds" method without data in cache', function () {
obj.hasInCache = jasmine.createSpy().and.returnValue(false);
obj.setIds(currency, store, ids);
expect(obj.hasInCache).toHaveBeenCalledWith(currency, store, ids);
expect(obj.loadDataFromServer).toHaveBeenCalledWith(currency, store, ids);
expect(obj.data.valueHasMutated).not.toHaveBeenCalled();
});
it('check calls "setIds" method with data in cache', function () {
obj.hasInCache = jasmine.createSpy().and.returnValue(true);
obj.setIds(currency, store, ids);
expect(obj.hasInCache).toHaveBeenCalledWith(currency, store, ids);
expect(obj.loadDataFromServer).not.toHaveBeenCalled();
expect(obj.data.valueHasMutated).toHaveBeenCalled();
});
});
describe('"getDataByIdentifiers" method', function () {
var currency = 'currency',
store = '1',
productIdentifiers = {
'1': {
id: '1'
},
'2': {
id: '2'
}
};
beforeEach(function () {
obj.data = jasmine.createSpy().and.returnValue({
'1': {
value: 'firstValue'
},
'2': {
value: 'secondValue'
}
});
});
it('check calls "getDataByIdentifiers" with productIdentifiers', function () {
var result = obj.getDataByIdentifiers(currency, store, productIdentifiers);
expect(obj.data).toHaveBeenCalled();
expect(result['1'].value).toBe('firstValue');
expect(result['2'].value).toBe('secondValue');
});
it('check calls "getDataByIdentifiers" without productIdentifiers', function () {
var result = obj.getDataByIdentifiers(currency, store, {});
expect(obj.data).toHaveBeenCalled();
expect(typeof result).toBe('object');
expect(_.isEmpty(result)).toBe(true);
});
});
describe('"hasInCache" method', function () {
var currency = 'currency',
store = '1';
beforeEach(function () {
obj.data = jasmine.createSpy().and.returnValue({
'1': {
value: 'firstValue',
'currency_code': currency,
'store_id': store
},
'2': {
value: 'secondValue',
'currency_code': currency,
'store_id': store
}
});
});
it('check calls "hasInCache" with ids that exists in data', function () {
var ids = {
'1': {
id: '1',
'currency_code': currency,
'store_id': store
},
'2': {
id: '2',
'currency_code': currency,
'store_id': store
}
},
result = obj.hasInCache(currency, store, ids);
expect(obj.data).toHaveBeenCalled();
expect(result).toBe(true);
});
it('check calls "hasInCache" with ids that does not exists in data', function () {
var ids = {
'5': {
id: '5',
'currency_code': currency,
'store_id': store
},
'6': {
id: '6',
'currency_code': currency,
'store_id': store
}
},
result = obj.hasInCache(currency, store, ids);
expect(obj.data).toHaveBeenCalled();
expect(result).toBe(false);
});
});
describe('"loadDataFromServer" method', function () {
var currency = 'currency',
store = '1',
ids = {
'1': {
id: '1'
},
'2': {
id: '2'
}
};
beforeEach(function () {
obj.updateRequestConfig = {};
obj.hasIdsInSentRequest = jasmine.createSpy();
obj.request = {
sent: true
};
obj.data = jasmine.createSpy().and.returnValue({
'1': {
value: 'firstValue'
},
'2': {
value: 'secondValue'
}
});
});
it('check calls "loadDataFromServer" method inside "loadDataFromServer"', function () {
obj.loadDataFromServer(currency, store, ids);
expect(obj.hasIdsInSentRequest).toHaveBeenCalled();
});
it('check calls "hasInCache" with ids that exists in data', function () {
obj.loadDataFromServer(currency, store, ids);
expect(typeof obj.request).toBe('object');
});
it('check data in "updateRequestConfig" property', function () {
obj.loadDataFromServer(currency, store, ids);
expect(obj.updateRequestConfig.data['store_id']).toBe(store);
expect(obj.updateRequestConfig.data['currency_code']).toBe(currency);
});
});
describe('"hasIdsInSentRequest" method', function () {
var ids = {
'1': {
id: '1'
},
'2': {
id: '2'
}
};
beforeEach(function () {
obj.request = {
data: {
'1': {
data: 'value'
},
'2': {
data: 'value'
}
}
};
});
it('check calls "hasIdsInSentRequest" with empty request data', function () {
obj.request = {};
expect(obj.hasIdsInSentRequest(ids)).toBe(false);
});
it('check calls "hasIdsInSentRequest" with request data #1', function () {
expect(obj.hasIdsInSentRequest(ids)).toBe(true);
});
it('check calls "hasIdsInSentRequest" with request data #2', function () {
obj.request = {
data: {
'2': {
data: 'value'
}
}
};
expect(obj.hasIdsInSentRequest(ids)).toBe(false);
});
});
describe('"addDataFromPageCache" method', function () {
beforeEach(function () {
obj.providerHandler = jasmine.createSpy();
});
it('check calls "addDataFromPageCache" inside "addDataFromPageCache" method', function () {
obj.addDataFromPageCache({});
expect(obj.providerHandler).toHaveBeenCalled();
});
});
describe('"initProviderListener" method', function () {
beforeEach(function () {
obj.providerHandler = jasmine.createSpy();
});
it('check returned value', function () {
obj.initProviderListener();
expect(obj.initProviderListener()).toBe(obj);
expect(typeof obj.initProviderListener()).toBe('object');
});
});
describe('"cachesDataFromLocalStorage" method', function () {
it('check calls "getDataFromLocalStorage" and "data" method', function () {
var data = {};
obj.getDataFromLocalStorage = jasmine.createSpy().and.returnValue(data);
obj.data = jasmine.createSpy();
obj.cachesDataFromLocalStorage();
expect(obj.getDataFromLocalStorage).toHaveBeenCalled();
expect(obj.data).toHaveBeenCalledWith(data);
});
});
describe('"getDataFromLocalStorage" method', function () {
it('check calls localStorage get method', function () {
obj.localStorage = {
get: jasmine.createSpy()
};
obj.getDataFromLocalStorage();
expect(obj.localStorage.get).toHaveBeenCalled();
});
});
describe('"initLocalStorage" method', function () {
it('check localStorage', function () {
obj.namespace = 'test';
obj.initLocalStorage();
expect(typeof obj.localStorage).toBe('object');
});
it('check returned value', function () {
obj.namespace = 'test';
expect(typeof obj.initLocalStorage()).toBe('object');
expect(obj.initLocalStorage()).toBe(obj);
});
});
});
});
@@ -0,0 +1,68 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire',
'underscore'
], function ($, Squire, _) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy().and.returnValue({})
},
'Magento_Catalog/js/product/storage/ids-storage': {}
},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/storage/ids-storage-compare'], function (insance) {
obj = _.extend({}, insance);
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/product/storage/ids-storage-compare', function () {
describe('"providerDataHandler" method', function () {
it('check calls "prepareData" and "add" method', function () {
var data = {
property: 'value'
};
obj.prepareData = jasmine.createSpy().and.returnValue(data);
obj.add = jasmine.createSpy();
obj.providerDataHandler(data);
expect(obj.prepareData).toHaveBeenCalledWith(data);
expect(obj.add).toHaveBeenCalledWith(data);
});
});
describe('"prepareData" method', function () {
it('check returned value', function () {
var data = {
'1': {
id: '1'
}
},
result = obj.prepareData(data);
expect(typeof result[data['1'].id]).toBe('object');
expect(typeof result[data['1'].id]['added_at']).toBe('number');
expect(result[data['1'].id]['product_id']).toBe(data['1'].id);
});
});
});
});
@@ -0,0 +1,116 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire'
], function ($, Squire) {
'use strict';
var injector = new Squire(),
mocks = {},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/product/storage/ids-storage'], function (insance) {
obj = insance;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
window.localStorage.clear();
});
describe('Magento_Catalog/js/product/storage/ids-storage', function () {
describe('"getDataFromLocalStorage" method', function () {
it('check calls localStorage get method', function () {
obj.localStorage = {
get: jasmine.createSpy()
};
obj.getDataFromLocalStorage();
expect(obj.localStorage.get).toHaveBeenCalled();
});
});
describe('"initLocalStorage" method', function () {
it('check returned value', function () {
obj.namespace = 'test';
obj.initLocalStorage();
expect(typeof obj.localStorage).toBe('object');
});
});
describe('"initDataListener" method', function () {
it('check calls "subscribe"', function () {
obj.data = {
subscribe: jasmine.createSpy()
};
obj.initDataListener();
expect(obj.data.subscribe).toHaveBeenCalled();
});
});
describe('"internalDataHandler" method', function () {
var data = {
property: 'value'
};
beforeEach(function () {
obj.localStorage = {
get: jasmine.createSpy().and.returnValue(data),
set: jasmine.createSpy()
};
});
it('check calls with data that equal with data in localStorage', function () {
obj.internalDataHandler(data);
expect(window.localStorage.getItem(obj.namespace)).toBe(JSON.stringify(data));
});
it('check calls with data that not equal with data in localStorage', function () {
var emptyData = {};
obj.internalDataHandler(data);
obj.internalDataHandler(emptyData);
expect(window.localStorage.getItem(obj.namespace)).toBe(JSON.stringify(emptyData));
});
});
describe('"externalDataHandler" method', function () {
var data = {
firstProperty: 'firstValue'
};
beforeEach(function () {
obj.data = jasmine.createSpy().and.returnValue({
secondProperty: 'secondValue'
});
/**
* Mock for set method
*/
obj.set = function (param) {
this.result = param;
};
});
it('check calls with data', function () {
obj.externalDataHandler(data);
expect(obj.data).toHaveBeenCalled();
expect(obj.result.firstProperty).toBe('firstValue');
expect(obj.result.secondProperty).toBe('secondValue');
});
});
});
});
@@ -0,0 +1,128 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire'
], function ($, Squire) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Catalog/js/product/storage/data-storage': {},
'Magento_Catalog/js/product/storage/ids-storage-compare': {}
},
obj,
utils;
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/product/storage/storage-service', function () {
var config = {
namespace: 'namespace',
className: 'IdsStorage'
},
storage;
beforeEach(function (done) {
injector.mock(mocks);
injector.require([
'Magento_Catalog/js/product/storage/ids-storage',
'Magento_Catalog/js/product/storage/storage-service',
'mageUtils'
], function (IdsStorage, instance, mageUtils) {
obj = instance;
utils = mageUtils;
done();
});
});
describe('"createStorage" method', function () {
it('create new storage', function () {
obj.processSubscribers = jasmine.createSpy();
storage = obj.createStorage(config);
expect(obj.processSubscribers).toHaveBeenCalled();
expect(typeof storage).toBe('object');
});
});
describe('"processSubscribers" and "onStorageInit" method', function () {
var callback = jasmine.createSpy();
beforeEach(function () {
obj.onStorageInit('IdsStorage', callback);
});
it('test "processsubscribers" and "onStorageInit" method by proxy "createStorage" method', function () {
obj.onStorageInit(config.namespace, callback);
obj.createStorage(config);
expect(callback).toHaveBeenCalled();
});
});
describe('"getStorage" method', function () {
it('test returned value', function () {
obj.createStorage(config);
obj.getStorage(config.namespace);
expect(typeof obj.getStorage(config.namespace)).toBe('object');
});
});
describe('"add" method', function () {
var storageValue;
beforeEach(function () {
storage = new obj.createStorage(config);
storageValue = {
'property1': 1
};
storage.set(storageValue);
});
it('method exists', function () {
expect(storage.add).toBeDefined();
expect(typeof storage.add).toEqual('function');
});
it('update value', function () {
spyOn(utils, 'copy').and.callThrough();
expect(storage.get()).toEqual(storageValue);
storageValue = {
'property2': 2
};
storage.add(storageValue);
expect(utils.copy).toHaveBeenCalled();
expect(storage.get()).toEqual(
{
'property1': 1,
'property2': 2
}
);
});
it('add empty value', function () {
spyOn(utils, 'copy').and.callThrough();
storage.add({});
expect(utils.copy).not.toHaveBeenCalled();
expect(storage.get()).toEqual(
{
'property1': 1
}
);
});
});
});
});
@@ -0,0 +1,61 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire',
'jquery',
'ko'
], function (Squire, $, ko) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Catalog/js/product/view/product-ids': ko.observableArray([])
},
form = $(
'<form>' +
'<input type="hidden" name="product" value="1">' +
'</form>'
),
productIdResolver;
beforeAll(function (done) {
injector.mock(mocks);
injector.require(
[
'Magento_Catalog/js/product/view/product-ids-resolver'
], function (resolver) {
productIdResolver = resolver;
done();
}
);
});
describe('Magento_Catalog/js/product/view/product-ids-resolver', function () {
var dataProvider = [
{
ids: [],
expected: ['1']
},
{
ids: ['2', '3'],
expected: ['2', '3', '1']
},
{
ids: ['3', '1', '5'],
expected: ['3', '1', '5']
}
];
dataProvider.forEach(function (data) {
it('resolved product id\'s', function () {
mocks['Magento_Catalog/js/product/view/product-ids'](data.ids);
expect(productIdResolver(form)).toEqual(data.expected);
});
});
});
});
@@ -0,0 +1,237 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire',
'underscore'
], function ($, Squire, _) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Catalog/js/product/storage/storage-service': {
createStorage: jasmine.createSpy().and.returnValue({
get: jasmine.createSpy()
})
}
},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Catalog/js/storage-manager'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: '',
links: '',
listens: '',
storagesConfiguration: []
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Catalog/js/storage-manager', function () {
describe('"initStorages" method', function () {
beforeEach(function () {
obj.storagesConfiguration = {
first: {
savePrevious: false
},
second: {
savePrevious: false
}
};
obj.storagesNamespace = _.keys(obj.storagesConfiguration);
});
it('create new storage', function () {
obj.initStorages();
expect(typeof obj[obj.storagesNamespace[0]]).toBe('object');
expect(typeof obj[obj.storagesNamespace[1]]).toBe('object');
expect(typeof obj[obj.storagesNamespace[0]].previous).toBe('undefined');
expect(typeof obj[obj.storagesNamespace[1]].previous).toBe('undefined');
});
it('create new storage with saving previous', function () {
obj.storagesConfiguration.first.savePrevious = true;
obj.storagesConfiguration.second.savePrevious = true;
obj.initStorages();
expect(typeof obj[obj.storagesNamespace[0]].previous).toBe('object');
expect(typeof obj[obj.storagesNamespace[1]].previous).toBe('object');
});
it('check returned value', function () {
expect(obj.initStorages()).toBe(obj);
});
});
describe('"initStartData" method', function () {
it('check start data', function () {
obj.updateDataHandler = jasmine.createSpy();
obj.storagesNamespace = ['first', 'second'];
obj[obj.storagesNamespace[0]] = obj[obj.storagesNamespace[1]] = {
get: jasmine.createSpy()
};
obj.initStartData();
expect(obj.updateDataHandler).toHaveBeenCalledWith('first', obj[obj.storagesNamespace[0]].get());
expect(obj.updateDataHandler).toHaveBeenCalledWith('second', obj[obj.storagesNamespace[1]].get());
});
it('check returned value', function () {
expect(obj.initStartData()).toBe(obj);
});
});
describe('"prepareStoragesConfig" method', function () {
beforeEach(function () {
obj.storagesConfiguration = {
first: {
savePrevious: false,
requestConfig: {
url: '/path/'
}
},
second: {
savePrevious: false,
requestConfig: {
url: '/path/'
}
}
};
obj.requestConfig = {
additionalData: 'data'
};
});
it('check storagesNamespace', function () {
obj.prepareStoragesConfig();
expect(obj.storagesNamespace[0]).toBe('first');
expect(obj.storagesNamespace[1]).toBe('second');
});
it('check storage requestConfig', function () {
obj.prepareStoragesConfig();
expect(obj.storagesConfiguration.first.requestConfig.additionalData).toBe('data');
expect(obj.storagesConfiguration.second.requestConfig.additionalData).toBe('data');
});
it('check returned value', function () {
expect(obj.prepareStoragesConfig()).toBe(obj);
});
});
describe('"getUtcTime" method', function () {
it('check type of returned value', function () {
expect(typeof obj.getUtcTime()).toBe('number');
});
});
describe('"initUpdateStorageDataListener" method', function () {
it('check type of returned value', function () {
obj.storagesNamespace = ['first', 'second'];
obj.first = {
data: {
subscribe: jasmine.createSpy()
}
};
obj.second = {
data: {
subscribe: jasmine.createSpy()
}
};
expect(typeof obj.getUtcTime()).toBe('number');
});
});
describe('"updateDataHandler" method', function () {
var data = {
property: 'value'
},
name = 'first',
value = {
property: 'value'
},
lastUpdate = 1300000000,
utcTime = 1500000000,
lastUpdatePeriod = 100000000;
beforeEach(function () {
obj.getLastUpdate = jasmine.createSpy().and.returnValue(lastUpdate);
obj.getUtcTime = jasmine.createSpy().and.returnValue(utcTime);
obj.lastUpdatePeriod = lastUpdatePeriod;
obj.dataFilter = jasmine.createSpy().and.returnValue(value);
obj.sendRequest = jasmine.createSpy();
});
it('check calls with data that equal with previous data', function () {
obj[name] = {
set: jasmine.createSpy(),
previous: {
set: jasmine.createSpy(),
get: jasmine.createSpy().and.returnValue(data)
}
};
obj.updateDataHandler(name, data);
expect(obj.dataFilter).not.toHaveBeenCalled();
expect(obj.first.set).not.toHaveBeenCalled();
expect(obj.sendRequest).not.toHaveBeenCalled();
expect(obj.first.previous.get).toHaveBeenCalled();
expect(obj.first.previous.set).not.toHaveBeenCalled();
});
});
describe('"getLastUpdate" method', function () {
var getItem = window.localStorage.getItem;
beforeEach(function () {
window.localStorage.getItem = jasmine.createSpy().and.returnValue('value');
});
it('check calling "getItem" method of localStorage', function () {
var name = 'first';
obj[name] = {
namespace: 'namespace'
};
expect(obj.getLastUpdate(name)).toBe('value');
expect(window.localStorage.getItem).toHaveBeenCalledWith(obj[name].namespace + '_last_update');
});
afterEach(function () {
window.localStorage.getItem = getItem;
});
});
describe('"setLastUpdate" method', function () {
var setItem = window.localStorage.setItem;
beforeEach(function () {
window.localStorage.setItem = jasmine.createSpy().and.returnValue('value');
});
it('check calling "setItem" method of localStorage', function () {
var name = 'first',
utcTime = 1500000000;
obj[name] = {
namespace: 'namespace'
};
obj.getUtcTime = jasmine.createSpy().and.returnValue(utcTime);
obj.setLastUpdate(name);
expect(window.localStorage.setItem).toHaveBeenCalledWith(obj[name].namespace + '_last_update', utcTime);
});
afterEach(function () {
window.localStorage.setItem = setItem;
});
});
});
});
@@ -0,0 +1,30 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'Magento_Checkout/js/model/default-post-code-resolver'
], function (_, DefaultPostCodeResolver) {
'use strict';
describe('checkout/js/model/default-post-code-resolver', function () {
var defaultPostCodeResolver;
beforeEach(function () {
defaultPostCodeResolver = DefaultPostCodeResolver;
window.checkoutConfig = {
defaultPostcode: '19800'
};
});
it('resolve', function () {
expect(defaultPostCodeResolver.resolve()).toBeNull();
});
it('resolve with using default code', function () {
defaultPostCodeResolver.setUseDefaultPostCode(true);
expect(defaultPostCodeResolver.resolve()).toEqual('19800');
});
});
});
@@ -0,0 +1,44 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire'
], function (Squire) {
'use strict';
describe('Magento_Checkout/js/action/redirect-on-success', function () {
var injector = new Squire(),
RedirectOnSuccess,
FullScreenLoader;
beforeEach(function (done) {
window.checkoutConfig = {
defaultSuccessPageUrl: 'checkout/success'
};
injector.require(['Magento_Checkout/js/action/redirect-on-success',
'Magento_Checkout/js/model/full-screen-loader'], function (action, loader) {
RedirectOnSuccess = action;
FullScreenLoader = loader;
spyOn(FullScreenLoader, 'startLoader');
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
it('Checks if loader is called before redirect to success page.', function () {
spyOn(RedirectOnSuccess, 'redirectToSuccessPage').and.callFake(function () {});
RedirectOnSuccess.execute();
expect(FullScreenLoader.startLoader).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,87 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire',
'jquery'
], function (Squire, $) {
'use strict';
var injector = new Squire(),
setPaymentInformation,
serviceUrl = 'http://url',
mocks = {
'Magento_Checkout/js/model/quote': {
getQuoteId: jasmine.createSpy().and.returnValue(1),
billingAddress: jasmine.createSpy().and.returnValue(null)
},
'Magento_Checkout/js/model/url-builder': {
createUrl: jasmine.createSpy().and.returnValue(serviceUrl)
},
'mage/storage': {
post: function () {} // jscs:ignore jsDoc
},
'Magento_Customer/js/model/customer': {
isLoggedIn: jasmine.createSpy().and.returnValue(false)
},
'Magento_Checkout/js/model/full-screen-loader': {
startLoader: jasmine.createSpy(),
stopLoader: jasmine.createSpy()
},
'Magento_Checkout/js/action/get-totals': jasmine.createSpy('getTotalsAction'),
'Magento_Checkout/js/model/error-processor': jasmine.createSpy('errorProcessor')
};
beforeEach(function (done) {
injector.mock(mocks);
injector.require(
['Magento_Checkout/js/action/set-payment-information-extended'],
function (action) {
setPaymentInformation = action;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {
}
});
describe('Magento/Checkout/js/action/set-payment-information-extended', function () {
it('Checks that paymentData consist correct data value.', function () {
var messageContainer = jasmine.createSpy('messageContainer'),
deferral = new $.Deferred(),
paymentData = {
method: 'checkmo',
title: 'Method title',
additionalData: null,
__disableTmpl: {
title: true
}
},
payload = {
cartId: 1,
paymentMethod: {
method: 'checkmo',
additionalData: null
},
billingAddress: null
};
spyOn(mocks['mage/storage'], 'post').and.callFake(function () {
return deferral.resolve({});
});
setPaymentInformation(messageContainer, paymentData, false);
expect(mocks['Magento_Checkout/js/model/full-screen-loader'].startLoader).toHaveBeenCalled();
expect(mocks['mage/storage'].post)
.toHaveBeenCalledWith(serviceUrl, JSON.stringify(payload), true, 'application/json', {});
expect(mocks['Magento_Checkout/js/model/full-screen-loader'].stopLoader).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,113 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
/*jscs:disable jsDoc*/
define([
'squire', 'jquery', 'ko'
], function (Squire, $, ko) {
'use strict';
describe('Magento_Checkout/js/empty-cart', function () {
var injector = new Squire(),
cartData = ko.observable({}),
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy('get', function () {
return cartData;
}).and.callThrough(),
reload: jasmine.createSpy(),
getInitCustomerData: function () {}
}
},
deferred,
emptyCart;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/empty-cart'], function (instance) {
emptyCart = instance;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
cartData({});
});
describe('Check Cart data preparation process', function () {
it('Tests that Cart data is NOT checked before initialization', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
return deferred.promise();
});
expect(emptyCart()).toBe(undefined);
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].getInitCustomerData).toHaveBeenCalled();
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
});
it('Tests that Cart data does NOT reload if there are no items in it', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
});
cartData({
items: []
});
emptyCart();
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
});
it('Tests that Cart data is checked only after initialization', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
return deferred.promise();
});
cartData({
items: [1]
});
emptyCart();
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
deferred.resolve();
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalledWith(['cart'], false);
});
it('Tests that Cart data reloads if it has items', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
});
cartData({
items: [1]
});
emptyCart();
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalledWith(['cart'], false);
});
});
});
});
@@ -0,0 +1,121 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*jscs:disable jsDoc*/
/* eslint max-nested-callbacks: 0 */
define([
'squire',
'ko'
], function (Squire, ko) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Customer/js/customer-data': {
get: function () {
return ko.observable();
},
set: function () {}
}
},
cache;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/cart/cache'], function (Constr) {
cache = Constr;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/model/cart/cache', function () {
describe('Check the "get" method', function () {
it('Check default call with "cart-data" key', function () {
var expectedResult = JSON.stringify(cache.cartData);
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable(expectedResult));
expect(cache.get('cart-data')).toBe(expectedResult);
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart-data');
});
it('Get data from local storage when key does not exist.', function () {
var expectedResult = {
address: 'test'
};
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable(expectedResult));
expect(cache.get('address')).toBe('test');
expect(cache._getAddress).toBe(undefined);
});
});
describe('Check the "set" method', function () {
it('Check the return value to be undefined', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable({}));
expect(cache.set('test-key')).toBe(undefined);
});
it('Check if the value is set properly', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable({}));
expect(cache.set('test-key', 'test-value')).toBe(undefined);
expect(cache.get('test-key')).toBe('test-value');
});
it('Check if the object is set properly', function () {
var testObj = {
address: 'test',
address2: 'test2'
};
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable({}));
expect(cache.set('cart-data', testObj)).toBe(undefined);
expect(cache.get('address')).toBe('test');
expect(cache.get('address2')).toBe('test2');
});
});
describe('Check the "clear" method', function () {
it('Check if the "clear" method clears the value which was set', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(ko.observable({}));
expect(cache.set('test-key', 'test-value')).toBe(undefined);
expect(cache.get('test-key')).toBe('test-value');
expect(cache.clear('test-key')).toBe(undefined);
expect(cache.get('test-key')).toBe(null);
});
it(
'Check if the "clear" method resets the object to default value with the "cart-data" key received',
function () {
var expectedResult = JSON.stringify(cache.cartData),
storage = ko.observable({});
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(storage);
spyOn(mocks['Magento_Customer/js/customer-data'], 'set').and.callFake(function (key, value) {
storage(value);
});
expect(cache.set('test-key', 'test-value')).toBe(undefined);
expect(cache.get('test-key')).toBe('test-value');
expect(cache.clear('cart-data')).toBe(undefined);
expect(cache.get('test-key')).toBe(undefined);
expect(JSON.stringify(cache.get('cart-data'))).toBe(expectedResult);
}
);
});
});
});
@@ -0,0 +1,165 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*jscs:disable jsDoc*/
require.config({
map: {
'*': {
'Magento_Checkout/js/model/shipping-service': 'Magento_Checkout/js/model/shipping-service'
}
}
});
define([
'squire',
'ko'
], function (Squire, ko) {
'use strict';
var injector = new Squire(),
rates = 'flatrate',
totals = {
tax: 0.1,
totals: 10
},
mocks = {
'Magento_Checkout/js/model/quote': {
shippingAddress: ko.observable(),
isVirtual: function () {},
billingAddress: ko.observable(),
shippingMethod: ko.observable(),
setTotals: function () {},
getTotals: function () {}
},
'Magento_Checkout/js/model/shipping-rate-processor/new-address': {
getRates: jasmine.createSpy()
},
'Magento_Checkout/js/model/cart/totals-processor/default': {
estimateTotals: jasmine.createSpy()
},
'Magento_Checkout/js/model/shipping-service': {
setShippingRates: function () {},
isLoading: ko.observable(),
getShippingRates: function () {
return ko.observable(rates);
}
},
'Magento_Checkout/js/model/cart/cache': {
isChanged: function () {},
get: jasmine.createSpy().and.returnValues(rates, rates, totals),
set: jasmine.createSpy()
},
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy().and.returnValue(
ko.observable({
'data_id': 1
})
)
}
};
beforeEach(function (done) {
window.checkoutConfig = {
quoteData: {},
storeCode: 'US'
};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/cart/estimate-service'], function () {
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/model/cart/estimate-service', function () {
it('test subscribe when billingAddress was changed for virtual quote', function () {
spyOn(mocks['Magento_Checkout/js/model/quote'], 'isVirtual').and.returnValue(false);
mocks['Magento_Checkout/js/model/quote'].billingAddress({
id: 5,
getType: function () {
return 'address_type_test';
}
});
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals)
.not.toHaveBeenCalled();
});
it('test subscribe when shipping address wasn\'t changed for not virtual quote', function () {
spyOn(mocks['Magento_Checkout/js/model/quote'], 'isVirtual').and.returnValue(false);
spyOn(mocks['Magento_Checkout/js/model/quote'], 'getTotals').and.returnValue(false);
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'isChanged').and.returnValues(false, false);
spyOn(mocks['Magento_Checkout/js/model/shipping-service'], 'setShippingRates');
spyOn(mocks['Magento_Checkout/js/model/quote'], 'setTotals');
mocks['Magento_Checkout/js/model/quote'].shippingAddress({
id: 2,
getType: function () {
return 'address_type_test';
}
});
expect(mocks['Magento_Checkout/js/model/shipping-service'].setShippingRates).toHaveBeenCalledWith(rates);
expect(mocks['Magento_Checkout/js/model/quote'].setTotals).toHaveBeenCalledWith(totals);
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals)
.not.toHaveBeenCalled();
expect(mocks['Magento_Checkout/js/model/shipping-rate-processor/new-address'].getRates)
.toHaveBeenCalled();
});
it('test subscribe when shipping address was changed for virtual quote', function () {
spyOn(mocks['Magento_Checkout/js/model/quote'], 'isVirtual').and.returnValue(true);
mocks['Magento_Checkout/js/model/quote'].shippingAddress({
id: 1,
getType: function () {
return 'address_type_test';
}
});
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals)
.toHaveBeenCalled();
expect(mocks['Magento_Checkout/js/model/shipping-rate-processor/new-address'].getRates)
.toHaveBeenCalled();
});
it('test subscribe when shipping address was changed for not virtual quote', function () {
spyOn(mocks['Magento_Checkout/js/model/quote'], 'isVirtual').and.returnValue(false);
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'isChanged').and.returnValue(
true
);
spyOn(mocks['Magento_Checkout/js/model/shipping-service'], 'setShippingRates');
mocks['Magento_Checkout/js/model/quote'].shippingAddress({
id: 4,
getType: function () {
return 'address_type_test';
}
});
expect(mocks['Magento_Checkout/js/model/shipping-service'].setShippingRates)
.not.toHaveBeenCalledWith(rates);
expect(mocks['Magento_Checkout/js/model/cart/cache'].set).not.toHaveBeenCalled();
expect(mocks['Magento_Checkout/js/model/shipping-rate-processor/new-address'].getRates).toHaveBeenCalled();
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals)
.toHaveBeenCalled();
});
it('test subscribe when shipping method was changed', function () {
mocks['Magento_Checkout/js/model/quote'].shippingMethod('flatrate');
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals).toHaveBeenCalled();
});
it('test subscribe when billingAddress was changed for not virtual quote', function () {
spyOn(mocks['Magento_Checkout/js/model/quote'], 'isVirtual').and.returnValue(true);
mocks['Magento_Checkout/js/model/quote'].billingAddress({
id: 6,
getType: function () {
return 'address_type_test';
}
});
expect(mocks['Magento_Checkout/js/model/cart/totals-processor/default'].estimateTotals).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,142 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*jscs:disable jsDoc*/
require.config({
map: {
'*': {
'Magento_Checkout/js/model/resource-url-manager': 'Magento_Checkout/js/model/resource-url-manager'
}
}
});
define([
'squire',
'ko',
'jquery'
], function (Squire, ko, $) {
'use strict';
var injector = new Squire(),
result = {
totals: 10
},
address = {
countryId: 'US',
region: null,
regionId: 'California',
postcode: 90210
},
data = {
totals: result,
address: address,
cartVersion: 1,
shippingMethodCode: null,
shippingCarrierCode: null
},
mocks = {
'Magento_Checkout/js/model/resource-url-manager': {
getUrlForTotalsEstimationForNewAddress: jasmine.createSpy().and.returnValue(
'http://example.com'
)
},
'Magento_Checkout/js/model/quote': {
shippingMethod: ko.observable({
'method_code': 'flatrate',
'carrier_code': 'flatrate'
}),
totals: ko.observable({
'subtotal': 4
}),
setTotals: jasmine.createSpy()
},
'mage/storage': {
post: function () {}
},
'Magento_Checkout/js/model/totals': {
isLoading: jasmine.createSpy()
},
'Magento_Checkout/js/model/error-processor': {
process: jasmine.createSpy()
},
'Magento_Checkout/js/model/cart/cache': {
isChanged: function () {},
get: function () {},
set: jasmine.createSpy()
},
'Magento_Customer/js/customer-data': {
get: function () {
},
set: jasmine.createSpy()
}
},
defaultProcessor;
beforeEach(function (done) {
window.checkoutConfig = {
quoteData: {},
storeCode: 'US'
};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/cart/totals-processor/default'], function (Constr) {
defaultProcessor = Constr;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/model/cart/totals-processor/default', function () {
it('estimateTotals if data wasn\'t cached and request was successfully sent', function () {
var deferral = new $.Deferred();
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'isChanged').and.returnValue(true);
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(
ko.observable({
'data_id': 1
})
);
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'get');
spyOn(mocks['mage/storage'], 'post').and.callFake(function () {
data.shippingMethodCode = mocks['Magento_Checkout/js/model/quote'].shippingMethod()['method_code'];
data.shippingCarrierCode = mocks['Magento_Checkout/js/model/quote'].shippingMethod()['carrier_code'];
return deferral.resolve(result);
});
expect(defaultProcessor.estimateTotals(address)).toBe(deferral);
expect(mocks['Magento_Checkout/js/model/quote'].setTotals).toHaveBeenCalledWith(result);
expect(mocks['Magento_Checkout/js/model/totals'].isLoading.calls.argsFor(0)[0]).toBe(true);
expect(mocks['Magento_Checkout/js/model/totals'].isLoading.calls.argsFor(1)[0]).toBe(false);
expect(mocks['mage/storage'].post).toHaveBeenCalled();
});
it('estimateTotals if data wasn\'t cached and request returns error', function () {
var deferral = new $.Deferred();
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'isChanged').and.returnValue(true);
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(
ko.observable({
'data_id': 1
})
);
spyOn(mocks['Magento_Checkout/js/model/cart/cache'], 'get');
spyOn(mocks['mage/storage'], 'post').and.callFake(function () {
return deferral.reject('Error Message');
});
expect(defaultProcessor.estimateTotals(address)).toBe(deferral);
expect(mocks['Magento_Checkout/js/model/totals'].isLoading.calls.argsFor(0)[0]).toBe(true);
expect(mocks['Magento_Checkout/js/model/totals'].isLoading.calls.argsFor(1)[0]).toBe(false);
expect(mocks['mage/storage'].post).toHaveBeenCalled();
expect(mocks['Magento_Checkout/js/model/error-processor'].process).toHaveBeenCalledWith('Error Message');
});
});
});
@@ -0,0 +1,96 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint-disable max-nested-callbacks*/
/*jscs:disable jsDoc*/
define([
'squire',
'ko'
], function (Squire, ko) {
'use strict';
describe('Magento_Checkout/js/model/checkout-data-resolver', function () {
var injector = new Squire(),
checkoutDataResolver = null,
checkoutData = null,
quote = null;
beforeEach(function (done) {
var mocks = {
'Magento_Customer/js/model/address-list': ko.observableArray(),
'Magento_Checkout/js/model/quote': {
shippingAddress: ko.observable(null),
isVirtual: jasmine.createSpy().and.returnValue(false),
billingAddress: ko.observable(null),
shippingMethod: ko.observable(null)
},
'Magento_Checkout/js/checkout-data': {
getSelectedBillingAddress: jasmine.createSpy(),
getBillingAddressFromData: jasmine.createSpy(),
getNewCustomerBillingAddress: jasmine.createSpy(),
setBillingAddressFromData: jasmine.createSpy()
},
'Magento_Checkout/js/action/create-shipping-address': {},
'Magento_Checkout/js/action/select-shipping-address': {},
'Magento_Checkout/js/action/select-shipping-method': {},
'Magento_Checkout/js/model/payment-service': {},
'Magento_Checkout/js/action/select-payment-method': {}
};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/checkout-data-resolver'], function (instance) {
checkoutDataResolver = instance;
quote = mocks['Magento_Checkout/js/model/quote'];
checkoutData = mocks['Magento_Checkout/js/checkout-data'];
done();
});
window.checkoutConfig = window.checkoutConfig || {};
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {
}
delete window.checkoutConfig.billingAddressFromData;
delete window.checkoutConfig.isBillingAddressFromDataValid;
});
describe('resolveBillingAddress()', function () {
describe(
'billing address is resolved from checkoutConfig if it cannot be resolved from local storage',
function () {
it('billing address is selected if is valid', function () {
var billingAddressFromData = {
firstname: 'John',
lastname: 'Doe'
};
window.checkoutConfig.isBillingAddressFromDataValid = true;
window.checkoutConfig.billingAddressFromData = billingAddressFromData;
checkoutDataResolver.resolveBillingAddress();
expect(checkoutData.setBillingAddressFromData).not.toHaveBeenCalledWith();
expect(quote.billingAddress().firstname).toEqual(billingAddressFromData.firstname);
expect(quote.billingAddress().lastname).toEqual(billingAddressFromData.lastname);
});
it('billing address is not selected and form is prefilled if it is not valid.', function () {
var billingAddressFromData = {
firstname: 'John',
lastname: 'Doe'
};
window.checkoutConfig.isBillingAddressFromDataValid = false;
window.checkoutConfig.billingAddressFromData = billingAddressFromData;
checkoutDataResolver.resolveBillingAddress();
expect(checkoutData.setBillingAddressFromData).toHaveBeenCalledWith(billingAddressFromData);
expect(quote.billingAddress()).toBeNull();
});
}
);
});
});
});
@@ -0,0 +1,75 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
define([
'squire'
], function (Squire) {
'use strict';
describe('Magento_Checkout/js/model/error-processor', function () {
var injector = new Squire(),
mocks = {
'mage/url': {
/** Method stub. */
build: jasmine.createSpy()
},
'Magento_Ui/js/model/messageList': jasmine.createSpy('globalList')
},
model;
beforeEach(function (done) {
injector.mock(mocks);
injector.require([
'Magento_Checkout/js/model/error-processor'
], function (processor) {
model = processor;
done();
});
});
describe('Check process method', function () {
it('check on success response with valid response data', function () {
var messageObject = {
message: 'Valid error message!'
},
messageContainer = jasmine.createSpyObj('globalMessageList', ['addErrorMessage']);
model.process({
status: 200,
responseText: JSON.stringify(messageObject)
}, messageContainer);
expect(messageContainer.addErrorMessage).toHaveBeenCalledWith(messageObject);
});
it('check on success response with invalid response data', function () {
var messageContainer = jasmine.createSpyObj('globalMessageList', ['addErrorMessage']),
messageObject = {
message: 'Something went wrong with your request. Please try again later.'
};
model.process({
status: 200,
responseText: ''
}, messageContainer);
expect(messageContainer.addErrorMessage)
.toHaveBeenCalledWith(messageObject);
});
it('check on failed status', function () {
var messageContainer = jasmine.createSpyObj('globalMessageList', ['addErrorMessage']);
spyOn(model, 'redirectTo').and.callFake(function () {});
model.process({
status: 401,
responseText: ''
}, messageContainer);
expect(mocks['mage/url'].build)
.toHaveBeenCalled();
});
});
});
});
@@ -0,0 +1,97 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'Magento_Checkout/js/model/new-customer-address'
], function (NewCustomerAddress) {
'use strict';
describe('Magento_Checkout/js/model/new-customer-address', function () {
var newCustomerAddress;
beforeEach(function () {
window.checkoutConfig = {
defaultCountryId: 'US'
};
newCustomerAddress = NewCustomerAddress;
});
it('Check that is executable.', function () {
expect(typeof newCustomerAddress).toEqual('function');
});
it('Check on empty object.', function () {
var result = newCustomerAddress({}),
expected = {
countryId: 'US',
regionCode: null,
region: null
};
result.postcode = undefined;
expect(JSON.stringify(result)).toEqual(JSON.stringify(expected));
});
it('Check on function call with empty address data.', function () {
var result = newCustomerAddress({});
expect(result.isDefaultShipping()).toBeUndefined();
expect(result.isDefaultBilling()).toBeUndefined();
expect(result.getType()).toEqual('new-customer-address');
expect(result.getKey()).toEqual('new-customer-address');
expect(result.getKey()).toContain('new-customer-address');
expect(result.isEditable()).toBeTruthy();
expect(result.canUseForBilling()).toBeTruthy();
});
it('Check on regionId with region object in address data.', function () {
var result = newCustomerAddress({
region: {
'region_id': 1
}
}),
expected = {
countryId: 'US',
regionId: 1
};
result.postcode = undefined;
expect(JSON.stringify(result)).toEqual(JSON.stringify(expected));
});
it('Check on regionId with countryId in address data.', function () {
var result = newCustomerAddress({
'country_id': 'US'
}),
expected = {
countryId: 'US',
regionCode: null,
region: null
};
result.postcode = undefined;
expect(JSON.stringify(result)).toEqual(JSON.stringify(expected));
});
it('Check that extensionAttributes property exists if defined', function () {
var result = newCustomerAddress({
'extension_attributes': {
'attr_code': 'val'
}
}),
expected = {
countryId: 'US',
regionCode: null,
region: null,
extensionAttributes: {
'attr_code': 'val'
}
};
result.postcode = undefined;
expect(JSON.stringify(result)).toEqual(JSON.stringify(expected));
});
});
});
@@ -0,0 +1,85 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire',
'ko'
], function (Squire, ko) {
'use strict';
let injector = new Squire(),
paymentService,
methods = [
{title: 'Credit Card', method: 'credit_card'},
{title: 'Stored Cards', method: 'credit_card_vault'}
],
mocksPaymentMethodCheckmo = {
'Magento_Checkout/js/model/quote': {
paymentMethod: ko.observable({
'method': 'checkmo'
})
}
},
mocksPaymentMethodVault = {
'Magento_Checkout/js/model/quote': {
paymentMethod: ko.observable({
'method': 'credit_card_vault_1'
})
}
};
beforeEach(function (done) {
window.checkoutConfig = {
vault: {
credit_card_vault: {}
},
payment: {
vault: {
credit_card_vault_1: {},
credit_card_vault_2: {}
}
}
};
done();
});
afterEach(function () {
try {
injector.remove();
injector.clean();
} catch (e) {}
});
describe('Magento_Checkout/js/model/payment-service', function () {
beforeEach(function (done) {
injector.mock(mocksPaymentMethodCheckmo);
// eslint-disable-next-line max-nested-callbacks
injector.require(['Magento_Checkout/js/model/payment-service'], function (instance) {
paymentService = instance;
done();
});
});
it('payment method is not enabled', function () {
paymentService.setPaymentMethods(methods);
expect(mocksPaymentMethodCheckmo['Magento_Checkout/js/model/quote'].paymentMethod()).toBeNull();
});
});
describe('Magento_Checkout/js/model/payment-service', function () {
beforeEach(function (done) {
injector.mock(mocksPaymentMethodVault);
// eslint-disable-next-line max-nested-callbacks
injector.require(['Magento_Checkout/js/model/payment-service'], function (instance) {
paymentService = instance;
done();
});
});
it('payment method is stored credit card', function () {
paymentService.setPaymentMethods(methods);
expect(mocksPaymentMethodVault['Magento_Checkout/js/model/quote'].paymentMethod().method)
.toEqual('credit_card_vault_1');
});
});
});
@@ -0,0 +1,105 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire',
'jquery',
'ko'
], function (Squire, $, ko) {
'use strict';
var injector = new Squire(),
mixin,
serviceUrl = 'rest/V1/guest-carts/estimate-shipping-methods',
mocks = {
'mage/storage': {
post: function () {} // jscs:ignore jsDoc
},
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy().and.returnValue(
ko.observable({
'data_id': 1
})
)
},
'Magento_Checkout/js/model/url-builder': {
createUrl: jasmine.createSpy().and.returnValue(serviceUrl)
}
};
describe('Magento_Checkout/js/model/shipping-rate-processor/new-address', function () {
beforeEach(function (done) {
window.checkoutConfig = {
'quoteData': {
'is_persistent': '0'
}
};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/shipping-rate-processor/new-address'], function (Mixin) {
mixin = Mixin;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
delete window.checkoutConfig.quoteData.is_persistent;
});
it('Check that estimate-shipping-methods API is called synchronously for persistent cart', function () {
var deferral = new $.Deferred();
window.checkoutConfig.quoteData.is_persistent = '1';
spyOn(mocks['mage/storage'], 'post').and.callFake(function () {
return deferral.resolve({});
});
mixin.getRates({
/** Stub */
'getCacheKey': function () {
return false;
}
});
expect(mocks['mage/storage'].post).toHaveBeenCalledWith(
serviceUrl,
'{"address":{}}',
false,
'application/json',
{},
false
);
});
it('Check that estimate-shipping-methods API is called asynchronously', function () {
var deferral = new $.Deferred();
spyOn(mocks['mage/storage'], 'post').and.callFake(function () {
return deferral.resolve({});
});
mixin.getRates({
/** Stub */
'getCacheKey': function () {
return false;
}
});
expect(mocks['mage/storage'].post).toHaveBeenCalledWith(
serviceUrl,
'{"address":{}}',
false,
'application/json',
{},
true
);
});
});
});
@@ -0,0 +1,86 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
/*jscs:disable jsDoc*/
define([
'squire', 'jquery', 'ko'
], function (Squire, $, ko) {
'use strict';
var injector = new Squire(),
cartData = {
'subtotalAmount': 10
},
cart = ko.observable(cartData),
cartDataTwo = {
'subtotalAmount': NaN
},
cartTwo = ko.observable(cartDataTwo),
mocks = {
'Magento_Checkout/js/model/quote': {
totals: ko.observable({
'subtotal': 4
})
},
'Magento_Customer/js/customer-data': {
get: function () {
return cart;
},
reload: jasmine.createSpy(),
getInitCustomerData: function () {}
}
},
mocksTwo = {
'Magento_Checkout/js/model/quote': {
totals: ko.observable({
'subtotal': 10
})
},
'Magento_Customer/js/customer-data': {
get: function () {
return cartTwo;
},
reload: jasmine.createSpy(),
getInitCustomerData: function () {}
}
};
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Test that customer data is reloaded when quote subtotal and cart subtotal are different', function () {
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/model/totals'], function () {
done();
});
});
it('Test that customer data is reloaded when quote subtotal and cart subtotal are different', function () {
expect(mocks['Magento_Checkout/js/model/quote'].totals().subtotal).toBe(4);
expect(cart().subtotalAmount).toBe(10);
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalled();
});
});
describe('Test that customer data is not reloaded when cart subtotal is NaN', function () {
beforeEach(function (done) {
injector.mock(mocksTwo);
injector.require(['Magento_Checkout/js/model/totals'], function () {
done();
});
});
it('Test that customer data is not reloaded when cart subtotal is NaN', function () {
expect(mocksTwo['Magento_Checkout/js/model/quote'].totals().subtotal).toBe(10);
expect(cartTwo().subtotalAmount).toBeNaN();
expect(mocksTwo['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,243 @@
/*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint-disable max-nested-callbacks*/
/*jscs:disable jsDoc*/
define([
'jquery',
'Magento_Checkout/js/region-updater'
], function ($) {
'use strict';
var regionJson = {
'config': {
'show_all_regions': true,
'regions_required': [
'US'
]
},
'US': {
'1': {
'code': 'AL',
'name': 'Alabama'
},
'2': {
'code': 'AK',
'name': 'Alaska'
},
'3': {
'code': 'AS',
'name': 'American Samoa'
}
},
'DE': {
'81': {
'code': 'BAY',
'name': 'Bayern'
},
'82': {
'code': 'BER',
'name': 'Berlin'
},
'83': {
'code': 'BRG',
'name': 'Brandenburg'
}
}
},
defaultCountry = 'GB',
countries = {
'': '',
'US': 'United States',
'GB': 'United Kingdom',
'DE': 'Germany',
'IT': 'Italy'
},
regions = {
'': 'Please select a region, state or province.'
},
countryEl,
regionSelectEl,
regionInputEl,
postalCodeEl,
formEl,
containerEl;
function createFormField() {
var fieldWrapperEl = document.createElement('div'),
labelEl = document.createElement('label'),
inputControlEl = document.createElement('div'),
i;
fieldWrapperEl.appendChild(labelEl);
fieldWrapperEl.appendChild(inputControlEl);
for (i = 0; i < arguments.length; i++) {
inputControlEl.appendChild(arguments[i]);
}
labelEl.setAttribute('class', 'label');
fieldWrapperEl.setAttribute('class', 'field required');
inputControlEl.setAttribute('class', 'control');
return fieldWrapperEl;
}
function buildSelectOptions(select, options, defaultOption) {
var optionValue,
optionEl;
defaultOption = typeof defaultOption === 'undefined' ? '' : defaultOption;
// eslint-disable-next-line guard-for-in
for (optionValue in options) {
if (options.hasOwnProperty(optionValue)) {
optionEl = document.createElement('option');
optionEl.setAttribute('value', optionValue);
optionEl.textContent = countries[optionValue];
// eslint-disable-next-line max-depth
if (defaultOption === optionValue) {
optionEl.setAttribute('selected', 'selected');
}
select.add(optionEl);
}
}
}
function init(config) {
var defaultConfig = {
'optionalRegionAllowed': true,
'regionListId': '#' + regionSelectEl.id,
'regionInputId': '#' + regionInputEl.id,
'postcodeId': '#' + postalCodeEl.id,
'form': '#' + formEl.id,
'regionJson': regionJson,
'defaultRegion': 0,
'countriesWithOptionalZip': ['GB']
};
$(countryEl).regionUpdater($.extend({}, defaultConfig, config || {}));
}
beforeEach(function () {
containerEl = document.createElement('div');
formEl = document.createElement('form');
regionSelectEl = document.createElement('select');
regionInputEl = document.createElement('input');
postalCodeEl = document.createElement('input');
countryEl = document.createElement('select');
regionSelectEl.setAttribute('id', 'region_id');
regionSelectEl.setAttribute('style', 'display:none;');
regionInputEl.setAttribute('id', 'region');
regionInputEl.setAttribute('style', 'display:none;');
countryEl.setAttribute('id', 'country');
postalCodeEl.setAttribute('id', 'zip');
formEl.setAttribute('id', 'test_form');
formEl.appendChild(createFormField(countryEl));
formEl.appendChild(createFormField(regionSelectEl, regionInputEl));
formEl.appendChild(createFormField(postalCodeEl));
containerEl.appendChild(formEl);
buildSelectOptions(regionSelectEl, regions);
buildSelectOptions(countryEl, countries, defaultCountry);
document.body.appendChild(containerEl);
});
afterEach(function () {
$(containerEl).remove();
formEl = undefined;
containerEl = undefined;
regionSelectEl = undefined;
regionInputEl = undefined;
postalCodeEl = undefined;
countryEl = undefined;
});
describe('Magento_Checkout/js/region-updater', function () {
it('Check that default country is selected', function () {
init();
expect($(countryEl).val()).toBe(defaultCountry);
});
it('Check that region list is not displayed when selected country has no predefined regions', function () {
init();
$(countryEl).val('GB').trigger('change');
expect($(regionInputEl).is(':visible')).toBe(true);
expect($(regionInputEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).is(':visible')).toBe(false);
expect($(regionSelectEl).is(':disabled')).toBe(true);
});
it('Check country that has predefined and optional regions', function () {
init();
$(countryEl).val('DE').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(true);
expect($(regionSelectEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).hasClass('required-entry')).toBe(false);
expect($(regionInputEl).is(':visible')).toBe(false);
expect(
$(regionSelectEl).find('option')
.map(function () {
return this.textContent;
})
.get()
).toContain('Berlin');
});
it('Check country that has predefined and required regions', function () {
init();
$(countryEl).val('US').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(true);
expect($(regionSelectEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).hasClass('required-entry')).toBe(true);
expect($(regionInputEl).is(':visible')).toBe(false);
expect(
$(regionSelectEl).find('option')
.map(function () {
return this.textContent;
})
.get()
).toContain('Alaska');
});
it('Check that region fields are not displayed for country with optional regions if configured', function () {
init({
optionalRegionAllowed: false
});
$(countryEl).val('DE').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(false);
expect($(regionInputEl).is(':visible')).toBe(false);
});
it('Check that initial values are not overwritten - region input', function () {
$(countryEl).val('GB');
$(regionInputEl).val('Liverpool');
$(postalCodeEl).val('L13 0AL');
init();
expect($(countryEl).val()).toBe('GB');
expect($(regionInputEl).val()).toBe('Liverpool');
expect($(postalCodeEl).val()).toBe('L13 0AL');
});
it('Check that initial values are not overwritten - region select', function () {
$(countryEl).val('US');
$(postalCodeEl).val('99501');
init({
defaultRegion: '2'
});
expect($(countryEl).val()).toBe('US');
expect($(regionSelectEl).find('option:selected').text()).toBe('Alaska');
expect($(postalCodeEl).val()).toBe('99501');
});
it('Check that region values are cleared out on country change - region input', function () {
$(countryEl).val('GB');
$(regionInputEl).val('Liverpool');
init();
$(countryEl).val('IT').trigger('change');
expect($(countryEl).val()).toBe('IT');
expect($(regionInputEl).val()).toBe('');
});
it('Check that region values are cleared out on country change - region select', function () {
$(countryEl).val('US');
init({
defaultRegion: '2'
});
$(countryEl).val('DE').trigger('change');
expect($(countryEl).val()).toBe('DE');
expect($(regionSelectEl).val()).toBe('');
});
});
});
@@ -0,0 +1,116 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
/*jscs:disable jsDoc*/
define([
'squire',
'jquery',
'ko'
], function (Squire, $, ko) {
'use strict';
describe('Magento_Checkout/js/sidebar', function () {
var injector = new Squire(),
mocks = {
'Magento_Customer/js/customer-data': {
get: function () {
return ko.observable();
}
}
},
sidebar,
cartData = {
'items': [
{
'item_id': 1,
'product_sku': 'bundle',
'product_id': '1'
},
{
'item_id': 5,
'product_sku': 'simple',
'product_id': '5'
},
{
'item_id': 7,
'product_sku': 'configurable',
'product_id': '7'
}
]
},
cart = ko.observable(cartData);
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/sidebar'], function (Constr) {
sidebar = new Constr;
done();
});
});
describe('Check remove mini-cart item callback.', function () {
beforeEach(function () {
spyOn(jQuery.fn, 'trigger');
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(cart);
});
it('Method "_removeItemAfter" is defined', function () {
expect(sidebar._removeItemAfter).toBeDefined();
});
it('Cart item is exists', function () {
var elem = $('<input>').data('cart-item', 5);
sidebar._removeItemAfter(elem);
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(jQuery('body').trigger).toHaveBeenCalledWith('ajax:removeFromCart', {
'productIds': ['5'], 'productInfo': [{
'id': '5'
}]
});
});
it('Cart item doesn\'t exists', function () {
var elem = $('<input>').data('cart-item', 100);
sidebar._removeItemAfter(elem);
expect(jQuery('body').trigger).not.toHaveBeenCalled();
});
});
describe('Check update item quantity callback.', function () {
beforeEach(function () {
spyOn(jQuery.fn, 'trigger');
spyOn(mocks['Magento_Customer/js/customer-data'], 'get').and.returnValue(cart);
});
it('Method "_updateItemQtyAfter" is defined', function () {
expect(sidebar._updateItemQtyAfter).toBeDefined();
});
it('Cart item is exists', function () {
var elem = $('<input>').data('cart-item', 5);
spyOn(sidebar, '_hideItemButton');
sidebar._updateItemQtyAfter(elem);
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(jQuery('body').trigger).toHaveBeenCalledWith('ajax:updateCartItemQty');
expect(sidebar._hideItemButton).toHaveBeenCalledWith(elem);
});
it('Cart item doesn\'t exists', function () {
var elem = $('<input>').data('cart-item', 100);
spyOn(sidebar, '_hideItemButton');
sidebar._updateItemQtyAfter(elem);
expect(jQuery('body').trigger).not.toHaveBeenCalled();
expect(sidebar._hideItemButton).toHaveBeenCalledWith(elem);
});
});
});
});
@@ -0,0 +1,108 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
define([
'squire',
'ko'
], function (Squire, ko) {
'use strict';
var injector = new Squire(),
checkoutData = jasmine.createSpyObj('checkoutData', ['setNewCustomerBillingAddress']),
mocks = {
'Magento_Checkout/js/checkout-data': checkoutData,
'Magento_Customer/js/customer-data': {
/** Stub */
get: function () {}
},
'Magento_Checkout/js/model/quote': {
/** Stub */
getQuoteId: function () {},
billingAddress: ko.observable(null),
/** Stub */
isVirtual: function () {
return false;
},
shippingAddress: ko.observable(null),
paymentMethod: ko.observable(null)
}
},
lastSelectedBillingAddress = {
city: 'Culver City',
company: 'Magento',
country_id: 'US',// jscs:ignore requireCamelCaseOrUpperCaseIdentifiers
firstname: 'John',
lastname: 'Doe',
postcode: '90230',
region: '',
region_id: '12',// jscs:ignore requireCamelCaseOrUpperCaseIdentifiers
street: {
0: '6161 West Centinela Avenue',
1: ''
},
telephone: '+15555555555'
},
billingAddress;
beforeEach(function (done) {
window.checkoutConfig = {
quoteData: {},
storeCode: 'US'
};
spyOn(mocks['Magento_Checkout/js/model/quote'], 'billingAddress').and.returnValue(lastSelectedBillingAddress);
injector.mock(mocks);
injector.require(['Magento_Checkout/js/view/billing-address'], function (Constr) {
billingAddress = new Constr;
billingAddress.source = {
/** Stub */
get: function () {
return [];
},
/** Stub */
set: function () {},
/** Stub */
trigger: function () {}
};
done();
});
});
describe('Magento_Checkout/js/view/billing-address', function () {
describe('"needCancelBillingAddressChanges" method', function () {
it('Test negative scenario', function () {
spyOn(billingAddress, 'cancelAddressEdit');
billingAddress.editAddress();
billingAddress.updateAddress();
billingAddress.needCancelBillingAddressChanges();
expect(billingAddress.cancelAddressEdit).not.toHaveBeenCalled();
});
it('Test that billing address editing was canceled automatically', function () {
spyOn(billingAddress, 'cancelAddressEdit');
billingAddress.editAddress();
billingAddress.needCancelBillingAddressChanges();
expect(billingAddress.cancelAddressEdit).toHaveBeenCalled();
});
});
describe('"restoreBillingAddress" method', function () {
it('Test that lastSelectedBillingAddress was restored correctly', function () {
billingAddress.editAddress();
billingAddress.restoreBillingAddress();
expect(checkoutData.setNewCustomerBillingAddress).toHaveBeenCalledWith(lastSelectedBillingAddress);
});
});
});
});
@@ -0,0 +1,122 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
define(['squire', 'ko'], function (Squire, ko) {
'use strict';
var injector = new Squire(),
checkoutProvider = {
on: jasmine.createSpy()
},
mocks = {
'Magento_Checkout/js/action/select-shipping-address': jasmine.createSpy(),
'Magento_Checkout/js/model/address-converter': {
formAddressDataToQuoteAddress: jasmine.createSpy()
},
'Magento_Checkout/js/model/cart/estimate-service': jasmine.createSpy(),
'Magento_Checkout/js/checkout-data': jasmine.createSpy(),
'Magento_Checkout/js/model/shipping-rates-validator': {
bindChangeHandlers: jasmine.createSpy()
},
'uiRegistry': {
async: jasmine.createSpy().and.returnValue(function (callback) {
callback(checkoutProvider);
}),
create: jasmine.createSpy(),
get: jasmine.createSpy(),
set: jasmine.createSpy()
},
'Magento_Checkout/js/model/quote': {
isVirtual: jasmine.createSpy(),
shippingAddress: jasmine.createSpy()
},
'Magento_Checkout/js/model/checkout-data-resolver': {
resolveEstimationAddress: jasmine.createSpy()
},
'mage/validation': jasmine.createSpy()
},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/view/cart/shipping-estimation'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: ''
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/view/cart/shipping-estimation', function () {
describe('"initElement" method', function () {
it('Check for return value and element that initiated.', function () {
var element = jasmine.createSpyObj('element', ['initContainer']);
expect(obj.initElement(element)).toBe(obj);
expect(mocks['Magento_Checkout/js/model/shipping-rates-validator'].bindChangeHandlers)
.not.toHaveBeenCalled();
});
it('Check shipping rates validator call.', function () {
var element = {
index: 'address-fieldsets',
elems: ko.observable(),
initContainer: jasmine.createSpy()
};
spyOn(element.elems, 'subscribe');
obj.initElement(element);
expect(mocks['Magento_Checkout/js/model/shipping-rates-validator'].bindChangeHandlers)
.toHaveBeenCalledWith(element.elems(), true, 500);
expect(element.elems.subscribe)
.toHaveBeenCalledWith(jasmine.any(Function));
});
});
describe('"getEstimationInfo" method', function () {
it('Check for invalid form data.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValue(true),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.getEstimationInfo()).toBeUndefined();
expect(obj.source.get).toHaveBeenCalledWith('params.invalid');
expect(obj.source.get).not.toHaveBeenCalledWith('shippingAddress');
expect(obj.source.set).toHaveBeenCalledWith('params.invalid', false);
expect(obj.source.trigger).toHaveBeenCalledWith('shippingAddress.data.validate');
expect(mocks['Magento_Checkout/js/action/select-shipping-address']).not.toHaveBeenCalled();
obj.source = {};
});
it('Check for vaild form data.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValues(false, {}),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.getEstimationInfo()).toBeUndefined();
expect(obj.source.get).toHaveBeenCalledWith('params.invalid');
expect(obj.source.get).toHaveBeenCalledWith('shippingAddress');
expect(obj.source.set).toHaveBeenCalledWith('params.invalid', false);
expect(obj.source.trigger).toHaveBeenCalledWith('shippingAddress.data.validate');
expect(mocks['Magento_Checkout/js/action/select-shipping-address']).toHaveBeenCalled();
obj.source = {};
});
});
});
});
@@ -0,0 +1,84 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
define(['squire', 'ko', 'jquery', 'jquery/validate'], function (Squire, ko, $) {
'use strict';
describe('Magento_Checkout/js/view/form/element/email', function () {
var injector = new Squire(),
mocks = {
'Magento_Customer/js/model/customer': {
isLoggedIn: ko.observable()
},
'Magento_Customer/js/action/check-email-availability': jasmine.createSpy(),
'Magento_Customer/js/action/login': jasmine.createSpy(),
'Magento_Checkout/js/model/quote': {
isVirtual: jasmine.createSpy(),
shippingAddress: jasmine.createSpy()
},
'Magento_Checkout/js/checkout-data': jasmine.createSpyObj(
'checkoutData',
[
'setInputFieldEmailValue',
'setValidatedEmailValue',
'setCheckedEmailValue',
'getInputFieldEmailValue',
'getValidatedEmailValue',
'getCheckedEmailValue'
]
),
'Magento_Checkout/js/model/full-screen-loader': jasmine.createSpy()
},
Component;
beforeEach(function (done) {
window.checkoutConfig = {};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/view/form/element/email'], function (Constr) {
Component = new Constr({
provider: 'provName',
name: '',
index: '',
isPasswordVisible: false,
isEmailCheckComplete: null
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('"resolveInitialPasswordVisibility" method', function () {
it('Check return type of method.', function () {
expect(typeof Component.resolveInitialPasswordVisibility()).toEqual('boolean');
});
});
describe('"validateEmail" method', function () {
beforeEach(function () {
$('body').append('<form data-role="email-with-possible-login">' +
'<input type="text" name="username" />' +
'</form>');
spyOn($.fn, 'validate').and.returnValue(true);
});
it('Check if login form will be validated in case it is not visible', function () {
var loginFormSelector = 'form[data-role=email-with-possible-login]',
loginForm = $(loginFormSelector);
loginForm.hide();
Component.validateEmail();
expect(loginForm.is(':visible')).toBeFalsy();
expect(loginForm.validate).not.toHaveBeenCalled();
});
});
});
});
@@ -0,0 +1,99 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
// jscs:disable jsDoc
define(['squire'], function (Squire) {
'use strict';
var injector = new Squire(),
obj;
beforeEach(function (done) {
window.checkout = {
maxItemsToDisplay: 1
};
injector.require(['Magento_Checkout/js/view/minicart'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: '',
cart: {
items: function () {
return [
{
itemId: 1
},
{
itemId: 2
}
];
}
},
itemRenderer: {
'simpleProductType': 'customRenderer'
}
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/view/minicart', function () {
describe('"getCartItems" method', function () {
it('Check for return value.', function () {
var expectedResult = JSON.stringify([
{
itemId: 2
}
]);
expect(obj.getCartItems().length).toBe(1);
expect(JSON.stringify(obj.getCartItems())).toBe(expectedResult);
});
});
describe('"getCartLineItemsCount" method', function () {
it('Check for return value.', function () {
expect(obj.getCartLineItemsCount()).toBe(2);
});
});
describe('"getItemRenderer" method', function () {
describe('Returns different renderers by product type', function () {
it('Check for default renderer.', function () {
expect(obj.getItemRenderer('undefinedProductType')).toBe('defaultRenderer');
});
it('Check for custom renderer.', function () {
expect(obj.getItemRenderer('simpleProductType')).toBe('customRenderer');
});
});
});
describe('"getCartParam" method', function () {
it('Check for return value.', function () {
var expectedResult = JSON.stringify([
{
itemId: 1
},
{
itemId: 2
}
]);
expect(obj.getCartParam('items').length).toBe(2);
expect(JSON.stringify(obj.getCartParam('items'))).toBe(expectedResult);
});
});
});
});
@@ -0,0 +1,236 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
require.config({
map: {
'*': {
'Magento_Checkout/js/view/shipping': 'Magento_Checkout/js/view/shipping'
}
}
});
define(['squire', 'ko', 'jquery', 'jquery/validate'], function (Squire, ko, $) {
'use strict';
var injector = new Squire(),
modalStub = {
openModal: jasmine.createSpy(),
closeModal: jasmine.createSpy()
},
country = {
/** Stub */
on: function () {},
/** Stub */
get: function () {},
/** Stub */
set: function () {}
},
mocks = {
'Magento_Customer/js/model/customer': {
isLoggedIn: ko.observable()
},
'Magento_Customer/js/model/address-list': ko.observableArray(),
'Magento_Checkout/js/model/address-converter': jasmine.createSpy(),
'Magento_Checkout/js/model/quote': {
isVirtual: jasmine.createSpy(),
shippingMethod: ko.observable()
},
'Magento_Checkout/js/action/create-shipping-address': jasmine.createSpy().and.returnValue(
jasmine.createSpyObj('newShippingAddress', ['getKey'])
),
'Magento_Checkout/js/action/select-shipping-address': jasmine.createSpy(),
'Magento_Checkout/js/model/shipping-rates-validator': jasmine.createSpy(),
'Magento_Checkout/js/model/shipping-address/form-popup-state': {
isVisible: ko.observable()
},
'Magento_Checkout/js/model/shipping-service': jasmine.createSpyObj('service', ['getShippingRates']),
'Magento_Checkout/js/action/select-shipping-method': jasmine.createSpy(),
'Magento_Checkout/js/model/shipping-rate-registry': jasmine.createSpy(),
'Magento_Checkout/js/action/set-shipping-information': jasmine.createSpy(),
'Magento_Checkout/js/model/step-navigator': jasmine.createSpyObj('navigator', ['registerStep']),
'Magento_Ui/js/modal/modal': jasmine.createSpy('modal').and.returnValue(modalStub),
'Magento_Checkout/js/model/checkout-data-resolver': jasmine.createSpyObj(
'dataResolver',
['resolveShippingAddress']
),
'Magento_Checkout/js/checkout-data': jasmine.createSpyObj(
'checkoutData',
[
'setSelectedShippingAddress',
'setNewCustomerShippingAddress',
'setSelectedShippingRate',
'getSelectedShippingRate'
]
),
'Magento_Ui/js/lib/registry/registry': {
async: jasmine.createSpy().and.returnValue(function () {}),
create: jasmine.createSpy(),
set: jasmine.createSpy(),
get: jasmine.createSpy().and.callFake(function (query) {
if (query === 'test.shippingAddress.shipping-address-fieldset.country_id') {
return country;
} else if (query === 'checkout.errors') {
return {};
}
})
},
'Magento_Checkout/js/model/shipping-rate-service': jasmine.createSpy()
},
obj;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Checkout/js/view/shipping'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: '',
popUpForm: {
options: {
buttons: {
save: {},
cancel: {}
}
}
}
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/view/shipping', function () {
describe('"navigate" method', function () {
it('Check for return value.', function () {
var step = {
isVisible: ko.observable(false)
};
expect(obj.navigate(step)).toBeUndefined();
expect(step.isVisible()).toBe(true);
});
});
describe('"getPopUp" method', function () {
it('Check for return value.', function () {
expect(obj.getPopUp()).toBe(modalStub);
expect(mocks['Magento_Ui/js/modal/modal']).toHaveBeenCalled();
mocks['Magento_Ui/js/modal/modal'].calls.reset();
});
it('Check on single modal call', function () {
expect(obj.getPopUp()).toBe(modalStub);
expect(mocks['Magento_Ui/js/modal/modal']).not.toHaveBeenCalled();
});
});
describe('"showFormPopUp" method', function () {
it('Check method call.', function () {
expect(obj.showFormPopUp()).toBeUndefined();
expect(obj.isFormPopUpVisible()).toBeTruthy();
expect(modalStub.openModal).toHaveBeenCalled();
});
});
describe('"saveNewAddress" method', function () {
it('Check method call with invalid form data.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValue(true),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.saveNewAddress()).toBeUndefined();
expect(obj.isNewAddressAdded()).toBeFalsy();
expect(modalStub.closeModal).not.toHaveBeenCalled();
});
it('Check method call with valid form data.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValues(true, false, {}),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.saveNewAddress()).toBeUndefined();
expect(obj.isNewAddressAdded()).toBeTruthy();
expect(modalStub.closeModal).toHaveBeenCalled();
});
});
describe('"selectShippingMethod" method', function () {
it('Check method call.', function () {
var shippingMethod = {
'carrier_code': 'carrier',
'method_code': 'method'
};
expect(obj.selectShippingMethod(shippingMethod)).toBeTruthy();
expect(mocks['Magento_Checkout/js/checkout-data'].setSelectedShippingRate)
.toHaveBeenCalledWith('carrier_method');
});
});
describe('"setShippingInformation" method', function () {
it('Check method call.', function () {
spyOn(obj, 'validateShippingInformation').and.returnValue(false);
expect(obj.setShippingInformation()).toBeUndefined();
});
});
describe('"validateShippingInformation" method', function () {
it('Check method call on negative cases.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValue(true),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.validateShippingInformation()).toBeFalsy();
expect(obj.errorValidationMessage()).toBe(
'The shipping method is missing. Select the shipping method and try again.'
);
spyOn(mocks['Magento_Checkout/js/model/quote'], 'shippingMethod').and.returnValue(true);
spyOn(mocks['Magento_Customer/js/model/customer'], 'isLoggedIn').and.returnValue(true);
expect(obj.validateShippingInformation()).toBeFalsy();
});
it('Check method call on positive case.', function () {
$('body').append('<form data-role="email-with-possible-login">' +
'<input type="text" name="username" />' +
'</form>');
obj.source = {
get: jasmine.createSpy().and.returnValue(true),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
obj.isFormInline = false;
spyOn(mocks['Magento_Checkout/js/model/quote'], 'shippingMethod').and.returnValue(true);
spyOn(mocks['Magento_Customer/js/model/customer'], 'isLoggedIn').and.returnValue(false);
spyOn($.fn, 'valid').and.returnValue(true);
expect(obj.validateShippingInformation()).toBeTruthy();
});
});
describe('"triggerShippingDataValidateEvent" method', function () {
it('Check method call.', function () {
obj.source = {
get: jasmine.createSpy().and.returnValue(true),
set: jasmine.createSpy(),
trigger: jasmine.createSpy()
};
expect(obj.triggerShippingDataValidateEvent()).toBeUndefined();
});
});
});
});
@@ -0,0 +1,113 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
// jscs:disable jsDoc
define(['squire'], function (Squire) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Checkout/js/model/totals': {
totals: function () {
return {
'items_qty': 13.0765
};
},
getItems: function () {
var observable = function () {
return [{
itemId: 1
}, {
itemId: 2
}];
};
observable.subscribe = function () {};
return observable;
}
},
'Magento_Checkout/js/model/quote': {
isVirtual: function () {
return false;
}
},
'Magento_Checkout/js/model/step-navigator': {
isProcessed: function () {
return true;
}
}
},
obj;
beforeEach(function (done) {
window.checkoutConfig = {
maxCartItemsToDisplay: 1,
cartUrl: 'url/to/cart'
};
injector.mock(mocks);
injector.require(['Magento_Checkout/js/view/summary/cart-items'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: '',
itemsTestStorage: [],
/**
* @param {*} items
*/
items: function (items) {
this.itemsTestStorage = items;
}
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Checkout/js/view/summary/cart-items', function () {
describe('"getItemsQty" method', function () {
it('Check for return value.', function () {
expect(obj.getItemsQty()).toBe(13.0765);
});
});
describe('"isItemsBlockExpanded" method', function () {
it('Check for return value.', function () {
expect(obj.isItemsBlockExpanded()).toBeTruthy();
});
});
describe('"getCartLineItemsCount" method', function () {
it('Check for return value.', function () {
expect(obj.getCartLineItemsCount()).toBe(2);
});
});
describe('"setItems" method', function () {
it('Check for return value.', function () {
var items = [{
itemId: 1
}, {
itemId: 2
}],
expectedResult = JSON.stringify([{
itemId: 2
}]);
expect(obj.setItems(items)).toBeUndefined();
expect(JSON.stringify(obj.itemsTestStorage)).toBe(expectedResult);
});
});
});
});
@@ -0,0 +1,77 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(['squire', 'jquery'], function (Squire, $) {
'use strict';
var injector = new Squire(),
agreementsBlockSelector = '.payment-method._active div.checkout-agreements',
agreementsBlock = $('<div class="payment-method _active"><div class="checkout-agreements"></div></div>'),
obj,
/**
* @param {Boolean} isChecked
* @return {Object}
*/
getCheckboxMock = function (isChecked) {
return $('<input type="checkbox" class="required-entry" name="some"/>').prop('checked', isChecked);
};
beforeEach(function (done) {
window.checkoutConfig = {
checkoutAgreements: {
isEnabled: true
}
};
$('body').append(agreementsBlock);
injector.require(['Magento_CheckoutAgreements/js/model/agreement-validator'], function (Validator) {
obj = Validator;
done();
});
});
afterEach(function () {
$('.payment-method._active').remove();
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_CheckoutAgreements/js/model/agreement-validator', function () {
describe('"validate" method', function () {
it('Check with non existing checkboxes', function () {
expect(obj.validate()).toBe(true);
});
it('Check with unchecked checkboxes', function () {
$(agreementsBlockSelector).html(getCheckboxMock(false));
expect(obj.validate()).toBe(false);
});
it('Check with checked checkboxes', function () {
$(agreementsBlockSelector).html(getCheckboxMock(true));
expect(obj.validate()).toBe(true);
});
it('Check with several checkboxes', function () {
$(agreementsBlockSelector).html(getCheckboxMock(true));
$(agreementsBlockSelector).append(getCheckboxMock(false));
expect(obj.validate()).toBe(false);
$(agreementsBlockSelector).html(getCheckboxMock(false));
$(agreementsBlockSelector).append(getCheckboxMock(false));
expect(obj.validate()).toBe(false);
$(agreementsBlockSelector).html(getCheckboxMock(true));
$(agreementsBlockSelector).append(getCheckboxMock(true));
expect(obj.validate()).toBe(true);
});
});
});
});
@@ -0,0 +1,62 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire'
], function (Squire) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Checkout/js/action/place-order': jasmine.createSpy('placeOrderAction'),
'Magento_CheckoutAgreements/js/model/agreements-assigner': jasmine.createSpy('agreementsAssigner')
},
defaultContext = require.s.contexts._,
mixin,
placeOrderAction;
beforeEach(function (done) {
window.checkoutConfig = {
checkoutAgreements: {
isEnabled: true
}
};
injector.mock(mocks);
injector.require([
'Magento_CheckoutAgreements/js/model/place-order-mixin',
'Magento_Checkout/js/action/place-order'
], function (Mixin, placeOrder) {
mixin = Mixin;
placeOrderAction = placeOrder;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_CheckoutAgreements/js/model/place-order-mixin', function () {
it('mixin is applied to Magento_Checkout/js/action/place-order', function () {
var placeOrderMixins = defaultContext.config.config.mixins['Magento_Checkout/js/action/place-order'];
expect(placeOrderMixins['Magento_CheckoutAgreements/js/model/place-order-mixin']).toBe(true);
});
it('Magento_CheckoutAgreements/js/model/agreements-assigner is called', function () {
var messageContainer = jasmine.createSpy('messageContainer'),
paymentData = {};
mixin(placeOrderAction)(paymentData, messageContainer);
expect(mocks['Magento_CheckoutAgreements/js/model/agreements-assigner'])
.toHaveBeenCalledWith(paymentData);
expect(mocks['Magento_Checkout/js/action/place-order'])
.toHaveBeenCalledWith(paymentData, messageContainer);
});
});
});
@@ -0,0 +1,63 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire'
], function (Squire) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Checkout/js/action/set-payment-information': jasmine.createSpy('placeOrderAction'),
'Magento_CheckoutAgreements/js/model/agreements-assigner': jasmine.createSpy('agreementsAssigner')
},
defaultContext = require.s.contexts._,
mixin,
placeOrderAction;
beforeEach(function (done) {
window.checkoutConfig = {
checkoutAgreements: {
isEnabled: true
}
};
injector.mock(mocks);
injector.require([
'Magento_CheckoutAgreements/js/model/set-payment-information-mixin',
'Magento_Checkout/js/action/set-payment-information'
], function (Mixin, setPaymentInformation) {
mixin = Mixin;
placeOrderAction = setPaymentInformation;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_CheckoutAgreements/js/model/set-payment-information-mixin', function () {
it('mixin is applied to Magento_Checkout/js/action/set-payment-information', function () {
var placeOrderMixins = defaultContext
.config.config.mixins['Magento_Checkout/js/action/set-payment-information'];
expect(placeOrderMixins['Magento_CheckoutAgreements/js/model/set-payment-information-mixin']).toBe(true);
});
it('Magento_CheckoutAgreements/js/model/agreements-assigner is called', function () {
var messageContainer = jasmine.createSpy('messageContainer'),
paymentData = {};
mixin(placeOrderAction)(messageContainer, paymentData);
expect(mocks['Magento_CheckoutAgreements/js/model/agreements-assigner'])
.toHaveBeenCalledWith(paymentData);
expect(mocks['Magento_Checkout/js/action/set-payment-information'])
.toHaveBeenCalledWith(messageContainer, paymentData);
});
});
});
@@ -0,0 +1,61 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
/* jscs:disable jsDoc*/
define([
'Magento_ConfigurableProduct/js/variations/steps/summary'
], function (Summary) {
'use strict';
describe('Magento_ConfigurableProduct/js/variations/steps/summary', function () {
let model, quantityFieldName, productDataFromGrid, productDataFromGridExpected;
beforeEach(function () {
quantityFieldName = 'quantity123';
model = new Summary({quantityFieldName: quantityFieldName});
productDataFromGrid = {
sku: 'testSku',
name: 'test name',
weight: 12.12312,
status: 1,
price: 333.333,
someField: 'someValue',
quantity: 10
};
productDataFromGrid[quantityFieldName] = 12;
productDataFromGridExpected = {
sku: 'testSku',
name: 'test name',
weight: 12.12312,
status: 1,
price: 333.333
};
});
describe('Check prepareProductDataFromGrid', function () {
it('Check call to prepareProductDataFromGrid method with qty', function () {
productDataFromGrid.qty = 3;
productDataFromGridExpected[quantityFieldName] = 3;
const result = model.prepareProductDataFromGrid(productDataFromGrid);
expect(result).toEqual(productDataFromGridExpected);
});
it('Check call to prepareProductDataFromGrid method without qty', function () {
const result = model.prepareProductDataFromGrid(productDataFromGrid);
expect(result).toEqual(productDataFromGridExpected);
});
});
});
});
@@ -0,0 +1,51 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_ConfigurableProduct/js/components/dynamic-rows-configurable',
'Magento_Ui/js/dynamic-rows/dynamic-rows'
], function ($, DynamicRowsConf, DynamicRows) {
'use strict';
describe('Magento_ConfigurableProduct/js/components/dynamic-rows-configurable', function () {
var model;
beforeEach(function () {
model = new DynamicRowsConf(new DynamicRows({
isEmpty: jasmine.createSpy().and.returnValue(1),
isShowAddProductButton: jasmine.createSpy().and.returnValue(1)
}));
});
it('Verify processingUnionInsertDat method', function () {
var expectedData = [],
mockData = [
{
attributes: 'Color: dsfsd',
sku: 'Conf&-sdfs'
},
{
attributes: 'Color: sdfs',
sku: 'Conf-dsfsd'
}
],
sourceMock = {
get: jasmine.createSpy().and.returnValue(['code1', 'code2']),
set: jasmine.createSpy().and.callFake(function (path, row) {
expectedData.push(row);
})
};
model.source = sourceMock;
model.processingUnionInsertData(mockData);
expect(model.source.get).toHaveBeenCalled();
expect(expectedData[1].sku).toBe('Conf&-sdfs');
});
});
});
@@ -0,0 +1,107 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(['squire'], function (Squire) {
'use strict';
var injector = new Squire(),
Component,
params = {
name: 'qty-element',
dataScope: '',
value: 1000,
setListeners: jasmine.createSpy().and.callFake(function () {
return this;
}),
setLinks: jasmine.createSpy().and.callFake(function () {
this.isConfigurable = false;
return this;
})
};
beforeEach(function (done) {
injector.require(
['Magento_ConfigurableProduct/js/components/qty-configurable'], function (QtyConfigurable) {
Component = QtyConfigurable;
done();
});
});
afterEach(function () {
try {
injector.remove();
injector.clean();
} catch (e) {
}
});
describe('Magento_ConfigurableProduct/js/components/qty-configurable', function () {
it('Product is not configurable by default', function () {
var component = new Component(params);
expect(component.disabled()).toBeFalse();
expect(component.value()).toEqual(1000);
});
it('State of component does not changed', function () {
var component = new Component(params);
expect(component.disabled()).toBeFalse();
component.value(99);
component.handleQtyValue(false);
expect(component.disabled()).toBeFalse();
expect(component.value()).toEqual(99);
});
it('Product changed to configurable', function () {
var component = new Component(params);
expect(component.disabled()).toBeFalse();
expect(component.value()).toEqual(1000);
component.handleQtyValue(true);
expect(component.disabled()).toBeTruthy();
expect(component.value()).toEqual('');
});
it('Product is configurable by default', function () {
var component = new Component($.extend({}, params, {
// eslint-disable-next-line max-nested-callbacks
setLinks: jasmine.createSpy().and.callFake(function () {
this.isConfigurable = true;
return this;
})
}));
expect(component.disabled()).toBeTruthy();
expect(component.value()).toEqual('');
});
it('Product changed from configurable to another one', function () {
var component = new Component($.extend({}, params, {
// eslint-disable-next-line max-nested-callbacks
setLinks: jasmine.createSpy().and.callFake(function () {
this.isConfigurable = true;
return this;
})
}));
expect(component.disabled()).toBeTruthy();
expect(component.value()).toEqual('');
component.value(100);
component.handleQtyValue(false);
expect(component.disabled()).toBeFalse();
expect(component.value()).toEqual(100);
});
});
});
@@ -0,0 +1,180 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'Magento_ConfigurableProduct/js/variations/variations'
], function (Variations) {
'use strict';
describe('Magento_ConfigurableProduct/js/variations/variations', function () {
var variation;
beforeEach(function () {
variation = new Variations();
variation.source = {
data: {}
};
});
it('checks that "serializeData" serializes data', function () {
var matrix = [
{
name: 'Product1',
attributes: 'Color: black',
price: 100
},
{
name: 'Product2',
attributes: 'Color: red',
price: 50
},
{
name: 'Product3',
attributes: 'Color: white',
price: 20
}
],
ids = [1, 2, 3],
resultMatrix = JSON.stringify(matrix),
resultIds = JSON.stringify(ids);
variation.source.data['configurable-matrix'] = matrix;
variation.source.data['associated_product_ids'] = ids;
variation.serializeData();
expect(variation.source.data['configurable-matrix']).toEqual(matrix);
expect(variation.source.data['associated_product_ids']).toEqual(ids);
expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);
expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);
});
it('checks that "serializeData" uses old data if there is no data to serialize', function () {
var matrix = [
{
name: 'Product4',
attributes: 'Color: grey',
price: 5
},
{
name: 'Product5',
attributes: 'Color: pink',
price: 70
},
{
name: 'Product6',
attributes: 'Color: brown',
price: 30
}
],
ids = [4, 5, 6],
resultMatrix = JSON.stringify(matrix),
resultIds = JSON.stringify(ids);
variation.source.data['configurable-matrix-serialized'] = JSON.stringify(matrix);
variation.source.data['associated_product_ids_serialized'] = JSON.stringify(ids);
variation.serializeData();
expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);
expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);
});
it('checks that "serializeData" works correctly if we have new data to be serialized', function () {
var matrix = [
{
name: 'Product7',
attributes: 'Color: yellow',
price: 10
},
{
name: 'Product8',
attributes: 'Color: green',
price: 200
},
{
name: 'Product9',
attributes: 'Color: blue',
price: 500
}
],
ids = [7, 8, 9],
resultMatrix = JSON.stringify(matrix),
resultIds = JSON.stringify(ids);
variation.source.data['configurable-matrix'] = matrix;
variation.source.data['associated_product_ids'] = ids;
variation.source.data['configurable-matrix-serialized'] = JSON.stringify(['some old data']);
variation.source.data['associated_product_ids_serialized'] = JSON.stringify(['some old data']);
variation.serializeData();
expect(variation.source.data['configurable-matrix']).toEqual(matrix);
expect(variation.source.data['associated_product_ids']).toEqual(ids);
expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);
expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);
});
it('checks that "unserializeData" unserializes data', function () {
var matrixString = '[{"name":"Small Product","attributes":"Size: small","price":5.5},' +
'{"name":"Medium Product","attributes":"Size: medium","price":10.99},' +
'{"name":"Large Product","attributes":"Size: large","price":25}]',
idString = '[100, 101, 102]',
resultMatrix = JSON.parse(matrixString),
resultIds = JSON.parse(idString);
variation.source.data['configurable-matrix-serialized'] = matrixString;
variation.source.data['associated_product_ids_serialized'] = idString;
variation.unserializeData();
expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();
expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();
expect(variation.source.data['configurable-matrix']).toEqual(resultMatrix);
expect(variation.source.data['associated_product_ids']).toEqual(resultIds);
});
it('checks that "serializeData" and "unserializeData" give proper result', function () {
var matrix = [
{
name: 'Small Product',
attributes: 'Size: small',
price: 5.50
},
{
name: 'Medium Product',
attributes: 'Size: medium',
price: 10.99
},
{
name: 'Large Product',
attributes: 'Size: large',
price: 25
}
],
ids = [1, 2, 3],
resultMatrix = JSON.stringify(matrix),
resultIds = JSON.stringify(ids);
variation.source.data['configurable-matrix'] = matrix;
variation.source.data['associated_product_ids'] = ids;
variation.serializeData();
expect(variation.source.data['configurable-matrix']).toEqual(matrix);
expect(variation.source.data['associated_product_ids']).toEqual(ids);
expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);
expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);
variation.unserializeData();
expect(variation.source.data['configurable-matrix']).toEqual(matrix);
expect(variation.source.data['associated_product_ids']).toEqual(ids);
expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();
expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();
});
});
});
@@ -0,0 +1,188 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_ConfigurableProduct/js/configurable'
], function ($, Configurable) {
'use strict';
var widget,
options = {
'spConfig': {
'attributes': {
'93': {
'id': '93',
'code': 'color',
'label': 'Color',
'options': [
{'id': '14', 'label': 'brown', 'products': ['2']},
{'id': '15', 'label': 'beige', 'products': ['3']}
],
'position': '0'
}
},
'template': '$<%- data.price %>',
'currencyFormat': '$%s',
'optionPrices': {
'2': {
'baseOldPrice': {'amount': 12},
'oldPrice': {'amount': 12},
'basePrice': {'amount': 12},
'finalPrice': {'amount': 12},
'tierPrices': [{'qty': 4, 'price': 8.4, 'percentage': 30, 'excl_tax_price': 8.4}],
'msrpPrice': {'amount': 0}
},
'3': {
'baseOldPrice': {'amount': 10},
'oldPrice': {'amount': 10},
'basePrice': {'amount': 10},
'finalPrice': {'amount': 10},
'tierPrices': [],
'msrpPrice': {'amount': 0}
}
},
'priceFormat': {
'pattern': '$%s',
'precision': 2,
'requiredPrecision': 2,
'decimalSymbol': '.',
'groupSymbol': ',',
'groupLength': 3,
'integerRequired': false
},
'prices': {
'baseOldPrice': {'amount': 10},
'oldPrice': {'amount': 10},
'basePrice': {'amount': 10},
'finalPrice': {'amount': 10}
},
'productId': '4',
'chooseText': 'Choose an Option...',
'images': [],
'index': { '2': {'93': '14'}, '3': {'93': '15'}},
'salable': []
}
},
blockHtml = '<div class="product-info-main">' +
'<div class="product-info-price">' +
'<div class="price-box price-final_price" data-role="priceBox">' +
'</div>' +
'</div>' +
'<div class="product-add-form">' +
'<form id="cart"/>' +
'<select name=\'super_attribute[93]\'' +
' data-selector=\'super_attribute[93]\'' +
' data-validate=\'{required:true}\'' +
' id=\'attribute93\'' +
' class=\'super-attribute-select\'>' +
'<option value=\'\'>Choose an Option...</option>' +
'<option value=\'14\'>brown +$2.00</option>' +
'<option value=\'15\'>beige</option>' +
'</select>' +
'<input id="qty"/>' +
'</form>' +
'</div>' +
'</div>',
selectElement,
qtyElement,
formElement;
describe('Magento_ConfigurableProduct/js/configurable', function () {
beforeEach(function () {
$(blockHtml).appendTo('body');
selectElement = $('#attribute93');
qtyElement = $('#qty');
formElement = $('#cart');
$.fn.trigFunc = $.fn.trigger;
$.fn.priceBoxFunc = $.fn.priceBox;
$.fn.priceBox = function () {
return {
prices: $.extend(true, {}, this.data('price-box'))
};
};
$('body').find('[data-role=priceBox]').data('price-box', $.extend(true, {}, options.spConfig.prices));
widget = new Configurable($.extend(true, {}, options), formElement);
});
afterEach(function () {
formElement.remove();
$.fn.trigger = $.fn.trigFunc;
$.fn.priceBox = $.fn.priceBoxFunc;
delete $.fn.trigFunc;
delete $.fn.priceBoxFunc;
});
it('check if attribute value is possible to be set as configurable option', function () {
expect($.mage.configurable).toBeDefined();
widget._parseQueryParams('93=14');
expect(widget.options.values['93']).toBe('14');
});
it('check that attribute value is not set if provided option does not exists', function () {
expect($.mage.configurable).toBeDefined();
widget._parseQueryParams('93=10');
expect(widget.options.values['93']).toBe(undefined);
});
it('check if widget will return correct price values in case option is selected or not.', function () {
var result;
result = widget._getPrices().prices;
expect(result.baseOldPrice.amount).toBe(0);
expect(result.oldPrice.amount).toBe(0);
expect(result.basePrice.amount).toBe(0);
expect(result.finalPrice.amount).toBe(0);
selectElement.val(14);
result = widget._getPrices().prices;
expect(result.baseOldPrice.amount).toBe(2);
expect(result.oldPrice.amount).toBe(2);
expect(result.basePrice.amount).toBe(2);
expect(result.finalPrice.amount).toBe(2);
});
it('check that price is reloaded on qty change', function () {
spyOn($.fn, 'trigger');
qtyElement.trigFunc('input');
expect($.fn.trigger)
.toHaveBeenCalledWith(
'updatePrice',
{
prices: {
baseOldPrice: {
amount: 0
},
oldPrice: {
amount: 0
},
basePrice: {
amount: 0
},
finalPrice: {
amount: 0
}
}
}
);
});
it('check if the _configureElement method is enabling configurable option or not', function () {
selectElement.val(14);
widget._configureElement(selectElement);
expect(widget).toBeTruthy();
});
it('check if the _clearSelect method is clearing the option selections or not', function () {
selectElement.empty();
widget._clearSelect(selectElement);
expect(widget).toBeTruthy();
});
it('check if the _getSimpleProductId method is returning simple product id or not', function () {
widget._getSimpleProductId(selectElement);
expect(widget).toBeTruthy();
});
});
});
@@ -0,0 +1,71 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'uiRegistry',
'Magento_Customer/js/form/components/form',
'jquery'
], function (_, registry, Constr, $) {
'use strict';
describe('Magento_Customer/js/form/components/form', function () {
var obj,
originaljQueryAjax;
beforeEach(function () {
originaljQueryAjax = $.ajax;
obj = new Constr({
provider: 'provName',
name: '',
index: ''
});
});
afterEach(function () {
$.ajax = originaljQueryAjax;
});
registry.set('provName', {
/** Stub */
on: function () {},
/** Stub */
get: function () {},
/** Stub */
set: function () {}
});
describe('"deleteAddress" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('deleteAddress')).toBeDefined();
});
it('Check method type', function () {
var type = typeof obj.deleteAddress;
expect(type).toEqual('function');
});
it('Check returned value if method called without arguments', function () {
expect(obj.deleteAddress()).toBeUndefined();
});
it('Check returned value type if method called without arguments', function () {
var type = typeof obj.deleteAddress();
expect(type).toEqual('undefined');
});
it('Should call not call ajax if arguments are empty', function () {
$.ajax = jasmine.createSpy();
spyOn(obj, 'deleteAddress');
expect(obj.deleteAddress()).toBeUndefined();
expect($.ajax).not.toHaveBeenCalled();
});
});
});
});
@@ -0,0 +1,75 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
/*jscs:disable jsDoc*/
define(['Magento_Customer/js/form/components/insert-listing'], function (Constr) {
'use strict';
describe('Magento_Customer/js/form/components/insert-listing', function () {
var obj,
ids = ['1', '2'],
data = {
action: 'delete',
data: {
selected: ids
}
},
selectionsProvider = {
selected: jasmine.createSpy().and.returnValue(ids),
deselect: jasmine.createSpy()
};
beforeEach(function () {
obj = new Constr({ name: 'content_name' });
});
describe('Check delete massaction process', function () {
it('Check call to deleteMassaction method', function () {
obj.deleteMassaction = {
call: jasmine.createSpy()
};
obj.onMassAction(data);
expect(obj.deleteMassaction.call).toHaveBeenCalledWith(obj, {
selected: ids
});
});
it('Check ids are retrieved from selections provider if they are NOT in data', function () {
obj._delete = jasmine.createSpy();
obj.selections = jasmine.createSpy().and.callFake(function () {
return selectionsProvider;
});
obj.onMassAction({
action: 'delete',
data: {}
});
expect(selectionsProvider.selected).toHaveBeenCalled();
selectionsProvider.selected.calls.reset();
expect(obj._delete).toHaveBeenCalledWith([1, 2]);
});
it('Check removal of default addresses and selections by provided ids', function () {
obj.source = {
get: jasmine.createSpy().and.returnValues(2, 3),
set: jasmine.createSpy()
};
obj.selections = jasmine.createSpy().and.callFake(function () {
return selectionsProvider;
});
obj.onMassAction(data);
expect(selectionsProvider.selected).not.toHaveBeenCalled();
expect(obj.source.get.calls.count()).toEqual(2);
expect(obj.source.set.calls.count()).toEqual(1);
expect(selectionsProvider.deselect.calls.count()).toEqual(2);
});
});
});
});
@@ -0,0 +1,529 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
/* jscs:disable jsDoc*/
define([
'underscore',
'squire',
'jquery',
'Magento_Customer/js/section-config',
'Magento_Customer/js/customer-data',
'jquery/jquery-storageapi'
], function (_, Squire, $, sectionConfig, customerData) {
'use strict';
var injector = new Squire(),
obj,
originaljQuery,
originalGetJSON,
originalReload,
originalIsEmpty,
originalEach,
cookieLifeTime = 3600,
sectionConfigSettings = {
baseUrls: [
'http://localhost/'
],
sections: {
'customer/account/loginpost': ['*'],
'checkout/cart/add': ['cart'],
'rest/*/v1/guest-carts/*/selected-payment-method': ['cart', 'checkout-data'],
'*': ['messages']
},
clientSideSections: [
'checkout-data',
'cart-data'
],
sectionNames: [
'customer',
'product_data_storage',
'cart',
'messages'
]
};
function init(config) {
var defaultConfig = {
sectionLoadUrl: 'http://localhost/customer/section/load/',
expirableSectionLifetime: 60, // minutes
expirableSectionNames: ['cart'],
cookieLifeTime: cookieLifeTime,
updateSessionUrl: 'http://localhost/customer/account/updateSession/'
};
customerData['Magento_Customer/js/customer-data']($.extend({}, defaultConfig, config || {}));
}
function setupLocalStorage(sections) {
var mageCacheStorage = {},
sectionDataIds = {};
_.each(sections, function (sectionData, sectionName) {
sectionDataIds[sectionName] = sectionData['data_id'];
if (typeof sectionData.content !== 'undefined') {
mageCacheStorage[sectionName] = sectionData;
}
});
$.localStorage.set(
'mage-cache-storage',
mageCacheStorage
);
$.cookieStorage.set(
'section_data_ids',
sectionDataIds
);
$.localStorage.set(
'mage-cache-timeout',
new Date(Date.now() + cookieLifeTime * 1000)
);
$.cookieStorage.set(
'mage-cache-sessid',
true
);
}
function clearLocalStorage() {
$.cookieStorage.set('section_data_ids', {});
if (window.localStorage) {
window.localStorage.clear();
}
}
describe('Magento_Customer/js/customer-data', function () {
beforeAll(function () {
clearLocalStorage();
});
beforeEach(function (done) {
originalGetJSON = $.getJSON;
sectionConfig['Magento_Customer/js/section-config'](sectionConfigSettings);
injector.require([
'underscore',
'Magento_Customer/js/customer-data'
], function (underscore, Constr) {
_ = underscore;
obj = Constr;
done();
});
});
afterEach(function () {
try {
$.getJSON = originalGetJSON;
clearLocalStorage();
injector.clean();
injector.remove();
} catch (e) {
}
});
describe('"init" method', function () {
var storageInvalidation = {
keys: function () {
return ['section'];
}
};
beforeEach(function () {
originalReload = obj.reload;
originalIsEmpty = _.isEmpty;
$.initNamespaceStorage('mage-cache-storage').localStorage;
$.initNamespaceStorage('mage-cache-storage-section-invalidation').localStorage;
spyOn(storageInvalidation, 'keys').and.returnValue(['section']);
});
afterEach(function () {
obj.reload = originalReload;
_.isEmpty = originalIsEmpty;
$.namespaceStorages = {};
});
it('Should be defined', function () {
expect(obj.hasOwnProperty('init')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
obj.initStorage();
expect(function () {
obj.init();
}).not.toThrow();
});
it('Calls "getExpiredSectionNames" method', function () {
spyOn(obj, 'getExpiredSectionNames').and.returnValue([]);
obj.init();
expect(obj.getExpiredSectionNames).toHaveBeenCalled();
});
it('Calls "reload" method when expired sections exist', function () {
spyOn(obj, 'getExpiredSectionNames').and.returnValue(['section']);
spyOn(obj, 'reload').and.returnValue(true);
obj.init();
expect(obj.reload).toHaveBeenCalled();
});
it('Calls "reload" method when expired sections do not exist', function () {
spyOn(obj, 'getExpiredSectionNames').and.returnValue([]);
spyOn(obj, 'reload').and.returnValue(true);
spyOn(_, 'isEmpty').and.returnValue(false);
obj.init();
expect(obj.reload).toHaveBeenCalled();
});
it('Check it does not request sections from the server if there are no expired sections', function () {
setupLocalStorage({
'catalog': { // without storage content
'data_id': Math.floor(Date.now() / 1000) + 60 // in 1 minute
}
});
$.getJSON = jasmine.createSpy().and.callFake(function () {
var deferred = $.Deferred();
return deferred.promise();
});
init();
expect($.getJSON).not.toHaveBeenCalled();
});
it('Check it requests sections from the server if there are expired sections', function () {
clearLocalStorage();
setupLocalStorage({
'customer': {
'data_id': Math.floor(Date.now() / 1000) + 60 // invalidated,
},
'cart': {
'data_id': Math.floor(Date.now() / 1000) - 61 * 60, // 61 minutes ago
'content': {}
},
'product_data_storage': {
'data_id': Math.floor(Date.now() / 1000) + 60, // in 1 minute
'content': {}
},
'catalog': {
'data_id': Math.floor(Date.now() / 1000) + 60 // invalid section,
},
'checkout': {
'data_id': Math.floor(Date.now() / 1000) - 61 * 60, // invalid section,
'content': {}
}
});
$.getJSON = jasmine.createSpy('$.getJSON').and.callFake(function () {
var deferred = $.Deferred();
return deferred.promise();
});
init();
expect($.getJSON).toHaveBeenCalledWith(
'http://localhost/customer/section/load/',
jasmine.objectContaining({
sections: 'cart,customer'
})
);
});
});
describe('"getExpiredSectionNames method', function () {
it('Should be defined', function () {
expect(obj.hasOwnProperty('getExpiredSectionNames')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
expect(function () {
obj.getExpiredSectionNames();
}).not.toThrow();
});
it('Check that result contains expired section names', function () {
setupLocalStorage({
'cart': {
'data_id': Math.floor(Date.now() / 1000) - 61 * 60, // 61 minutes ago
'content': {}
}
});
$.getJSON = jasmine.createSpy('$.getJSON').and.callFake(function () {
var deferred = $.Deferred();
return deferred.promise();
});
init();
expect(customerData.getExpiredSectionNames()).toEqual(['cart']);
});
it('Check that result does not contain unexpired section names', function () {
setupLocalStorage({
'cart': {
'data_id': Math.floor(Date.now() / 1000) + 60, // in 1 minute
'content': {}
}
});
init();
expect(customerData.getExpiredSectionNames()).toEqual([]);
});
it('Check that result contains invalidated section names', function () {
clearLocalStorage();
setupLocalStorage({
'cart': { // without storage content
'data_id': Math.floor(Date.now() / 1000) + 60 // in 1 minute
}
});
$.getJSON = jasmine.createSpy('$.getJSON').and.callFake(function () {
var deferred = $.Deferred();
return deferred.promise();
});
init();
expect(customerData.getExpiredSectionNames()).toEqual(['cart']);
});
it('Check that result does not contain unsupported section names', function () {
setupLocalStorage({
'catalog': { // without storage content
'data_id': Math.floor(Date.now() / 1000) + 60 // in 1 minute
}
});
init();
expect(customerData.getExpiredSectionNames()).toEqual([]);
});
});
describe('"get" method', function () {
it('Should be defined', function () {
expect(obj.hasOwnProperty('get')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
expect(function () {
obj.get();
}).not.toThrow();
});
});
describe('"set" method', function () {
beforeEach(function () {
originalEach = _.each;
});
afterEach(function () {
_.each = originalEach;
});
it('Should be defined', function () {
expect(obj.hasOwnProperty('set')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
_.each = jasmine.createSpy().and.returnValue(true);
expect(function () {
obj.set();
}).not.toThrow();
});
});
describe('"reload" method', function () {
beforeEach(function () {
originaljQuery = $;
$ = jQuery;
$.getJSON = jasmine.createSpy().and.callFake(function () {
var deferred = $.Deferred();
/**
* Mock Done Method for getJSON
* @returns object
*/
deferred.promise().done = function () {
return {
responseJSON: {
section: {}
}
};
};
return deferred.promise();
});
});
afterEach(function () {
$ = originaljQuery;
});
it('Should be defined', function () {
expect(obj.hasOwnProperty('reload')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
expect(function () {
obj.reload();
}).not.toThrow();
});
it('Check it returns proper sections object when passed array with a single section name', function () {
var result;
spyOn(sectionConfig, 'filterClientSideSections').and.returnValue(['section']);
$.getJSON = jasmine.createSpy().and.callFake(function (url, parameters) {
var deferred = $.Deferred();
/**
* Mock Done Method for getJSON
* @returns object
*/
deferred.promise().done = function () {
return {
responseJSON: {
section: {}
}
};
};
expect(parameters).toEqual(jasmine.objectContaining({
sections: 'section'
}));
return deferred.promise();
});
result = obj.reload(['section'], true);
expect(result).toEqual(jasmine.objectContaining({
responseJSON: {
section: {}
}
}));
});
it('Check it returns proper sections object when passed array with multiple section names', function () {
var result;
spyOn(sectionConfig, 'filterClientSideSections').and.returnValue(['cart,customer,messages']);
$.getJSON = jasmine.createSpy().and.callFake(function (url, parameters) {
var deferred = $.Deferred();
expect(parameters).toEqual(jasmine.objectContaining({
sections: 'cart,customer,messages'
}));
/**
* Mock Done Method for getJSON
* @returns object
*/
deferred.promise().done = function () {
return {
responseJSON: {
cart: {},
customer: {},
messages: {}
}
};
};
return deferred.promise();
});
result = obj.reload(['cart', 'customer', 'messages'], true);
expect(result).toEqual(jasmine.objectContaining({
responseJSON: {
cart: {},
customer: {},
messages: {}
}
}));
});
it('Check it returns all sections when passed wildcard string', function () {
var result;
$.getJSON = jasmine.createSpy().and.callFake(function (url, parameters) {
var deferred = $.Deferred();
expect(parameters).toEqual(jasmine.objectContaining({
'force_new_section_timestamp': true
}));
/**
* Mock Done Method for getJSON
* @returns object
*/
deferred.promise().done = function () {
return {
responseJSON: {
cart: {},
customer: {},
messages: {}
}
};
};
return deferred.promise();
});
result = obj.reload('*', true);
expect($.getJSON).toHaveBeenCalled();
expect(result).toEqual(jasmine.objectContaining({
responseJSON: {
cart: {},
customer: {},
messages: {}
}
}));
});
});
describe('"invalidated" method', function () {
it('Should be defined', function () {
expect(obj.hasOwnProperty('invalidate')).toBeDefined();
});
it('Does not throw before component is initialized', function () {
expect(function () {
obj.invalidate();
}).not.toThrow();
});
});
describe('"onAjaxComplete" method', function () {
it('Should not trigger reload if sections is empty', function () {
var jsonResponse, settings;
jsonResponse = jasmine.createSpy();
spyOn(sectionConfig, 'getAffectedSections').and.returnValue([]);
spyOn(obj, 'reload');
settings = {
type: 'POST',
url: 'http://test.local'
};
obj.onAjaxComplete(jsonResponse, settings);
expect(obj.reload).not.toHaveBeenCalled();
});
});
describe('"Magento_Customer/js/customer-data" method', function () {
it('Should be defined', function () {
expect(obj.hasOwnProperty('Magento_Customer/js/customer-data')).toBeDefined();
});
});
});
});
@@ -0,0 +1,110 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
/*jscs:disable jsDoc*/
define([
'squire', 'jquery', 'ko'
], function (Squire, $, ko) {
'use strict';
describe('Magento_Customer/js/customer-global-session-loader', function () {
var injector,
customer = ko.observable({}),
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy('get', function () {
return customer;
}).and.callThrough(),
reload: jasmine.createSpy('reload'),
getInitCustomerData: function () {}
}
},
deferred,
customerSessionLoader;
beforeAll(function () {
$('body').append('<div id="customerMenu" class="customer-menu">Customer Menu</div>');
});
beforeEach(function (done) {
injector = new Squire();
injector.mock(mocks);
injector.require(['Magento_Customer/js/customer-global-session-loader'], function (instance) {
customerSessionLoader = instance;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
injector = null;
} catch (e) {
console.log(e);
}
customer({});
});
afterAll(function () {
$('#customerMenu').remove();
});
describe('Check customer data preparation process', function () {
it('Tests that customer data does not reloads if it has first name defined', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
});
customer({
firstname: 'First Name'
});
customerSessionLoader();
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('customer');
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
});
it('Tests that customer data reloads after init, if customer first name is not there', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
return deferred.promise();
});
customer({
_data: null
});
customerSessionLoader();
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('customer');
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
deferred.resolve();
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalledWith([], false);
});
it('Tests that customer data reloads if customer data is not there', function () {
spyOn(mocks['Magento_Customer/js/customer-data'], 'getInitCustomerData').and.callFake(function () {
deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
});
expect(customerSessionLoader()).toBe(undefined);
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('customer');
expect(mocks['Magento_Customer/js/customer-data'].getInitCustomerData).toHaveBeenCalled();
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalledWith([], false);
});
});
});
});
@@ -0,0 +1,55 @@
/* eslint-disable max-nested-callbacks */
define([
'squire'
], function (Squire) {
'use strict';
var injector = new Squire(),
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy().and.returnValue({})
}
},
processor;
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_Customer/js/invalidation-processor'], function (Constr) {
processor = new Constr({
name: 'processor'
});
processor.invalidationRules = {
'website-rule': {
'Magento_Customer/js/invalidation-rules/website-rule': {
process: jasmine.createSpy()
}
}
};
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Customer/js/invalidation-processor', function () {
describe('"process" method', function () {
it('record status is 1', function () {
/* eslint-disable no-native-reassign */
var requireTmp = require;
require = jasmine.createSpy();
processor.process();
expect(require).toHaveBeenCalled();
require = requireTmp;
});
});
});
});
@@ -0,0 +1,62 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'Magento_Customer/js/model/customer/address'
], function (CustomerAddress) {
'use strict';
describe('Magento_Customer/js/model/customer/address', function () {
var customerAddress;
beforeEach(function () {
customerAddress = CustomerAddress;
});
it('Check that is executable.', function () {
expect(typeof customerAddress).toEqual('function');
});
it('Check on empty object.', function () {
var addressData = {
region: {}
},
expected = {
customAttributes: []
};
expect(JSON.stringify(customerAddress(addressData))).toEqual(JSON.stringify(expected));
});
it('Check on function call with empty address data.', function () {
var result = customerAddress({
region: {}
});
expect(result.isDefaultShipping()).toBeUndefined();
expect(result.isDefaultBilling()).toBeUndefined();
expect(result.getAddressInline()).toBeUndefined();
expect(result.getType()).toEqual('customer-address');
expect(result.getKey()).toContain('customer-address');
expect(result.getCacheKey()).toContain('customer-address');
expect(result.isEditable()).toBeFalsy();
expect(result.canUseForBilling()).toBeTruthy();
});
it('Check on regionId with region object in address data.', function () {
var result = customerAddress({
region: {
'region_id': 1
}
}),
expected = {
regionId: '1',
customAttributes: []
};
expect(JSON.stringify(result)).toEqual(JSON.stringify(expected));
});
});
});
@@ -0,0 +1,221 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
define(['squire'], function (Squire) {
'use strict';
var injector = new Squire(),
obj;
beforeEach(function (done) {
// injector.mock(mocks);
injector.require(['Magento_Customer/js/section-config'], function (Constr) {
obj = Constr;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Customer/js/section-config', function () {
describe('"getAffectedSections" method', function () {
it('Does not throw before component is initialized.', function () {
expect(function () {
obj.getAffectedSections('http://localhost.com/path');
}).not.toThrow();
});
it('Returns proper sections when URL contains base URL.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'path': [
'section'
]
},
baseUrls: [
'http://localhost.com/',
'https://localhost.com/'
]
});
expect(obj.getAffectedSections('https://localhost.com/path')).toEqual(['section']);
});
it('Returns proper sections when glob pattern is used at the end.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'path/*': [
'section'
]
},
baseUrls: [
'http://localhost.com/',
'https://localhost.com/'
]
});
expect(obj.getAffectedSections('https://localhost.com/path/subpath')).toEqual(['section']);
});
it('Returns proper sections when glob pattern is used inside.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'*/subpath': [
'section'
]
},
baseUrls: [
'http://localhost.com/',
'https://localhost.com/'
]
});
expect(obj.getAffectedSections('https://localhost.com/path/subpath')).toEqual(['section']);
});
it('Strips "index.php" suffix from provided URL.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'path': [
'section'
]
},
baseUrls: [
'http://localhost.com/'
]
});
expect(obj.getAffectedSections('http://localhost.com/path/index.php')).toEqual(['section']);
});
it('Adds sections for all URLs "*" to found ones.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'path': [
'section'
],
'*': [
'all'
]
},
baseUrls: [
'http://localhost.com/'
]
});
expect(obj.getAffectedSections('http://localhost.com/path')).toEqual(['section', 'all']);
});
it('Returns "*" sections for all URLs.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'*': [
'all'
]
},
baseUrls: [
'http://localhost.com/'
]
});
expect(obj.getAffectedSections('http://localhost.com/path')).toEqual(['all']);
});
it('Ignores capitalization in parts of URL.', function () {
obj['Magento_Customer/js/section-config']({
sections: {
'path': [
'section'
]
},
baseUrls: [
'http://localhost.com/'
]
});
expect(obj.getAffectedSections('http://localhost.com/PaTh')).toEqual(['section']);
});
});
describe('"filterClientSideSections" method', function () {
it('Does not throw before component is initialized.', function () {
expect(function () {
obj.filterClientSideSections();
}).not.toThrow();
});
it('Returns empty array when all sections are client side.', function () {
var sections = ['test'];
obj['Magento_Customer/js/section-config']({
clientSideSections: sections
});
expect(obj.filterClientSideSections(sections)).toEqual([]);
});
it('Filters out client side sections.', function () {
var allSections = ['test', 'client'],
clientSections = ['client'];
obj['Magento_Customer/js/section-config']({
clientSideSections: clientSections
});
expect(obj.filterClientSideSections(allSections)).toEqual(['test']);
});
});
describe('"isClientSideSection" method', function () {
it('Does not throw before component is initialized.', function () {
expect(function () {
obj.isClientSideSection();
}).not.toThrow();
});
it('Returns true if section is defined as client side.', function () {
obj['Magento_Customer/js/section-config']({
clientSideSections: ['client']
});
expect(obj.isClientSideSection('client')).toBe(true);
});
it('Returns false if section is not defined as client side.', function () {
obj['Magento_Customer/js/section-config']({
clientSideSections: ['client']
});
expect(obj.isClientSideSection('test')).toBe(false);
});
it('Returns false if section is not client side and sections are not defined.', function () {
obj['Magento_Customer/js/section-config']({
clientSideSections: []
});
expect(obj.isClientSideSection('test')).toBe(false);
});
});
describe('"getSectionNames" method', function () {
it('Does not throw before component is initialized.', function () {
expect(function () {
obj.getSectionNames();
}).not.toThrow();
});
it('Returns defined section names.', function () {
var sections = ['test'];
obj['Magento_Customer/js/section-config']({
sectionNames: sections
});
expect(obj.getSectionNames()).toBe(sections);
});
});
});
});
@@ -0,0 +1,40 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_Customer/js/validation'
], function ($) {
'use strict';
describe('Testing customer DOB validation to tolerate zeroes in the single digit dates', function () {
var params,
dataProvider;
dataProvider = [
{
format: 'M/d/Y',
date: '09/2/18',
expects: true
},
{
format: 'M/DD/Y',
date: '09/2/18',
expects: false
}
];
dataProvider.forEach(function (data) {
it('Test date validation for format ' + data.format, function () {
params = {
'dateFormat': data.format
};
expect($.validator.methods['validate-date']
.call($.validator.prototype, data.date, null, params)).toEqual(data.expects);
});
});
});
});
@@ -0,0 +1,129 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint max-nested-callbacks: 0 */
define(['squire', 'ko'], function (Squire, ko) {
'use strict';
var injector = new Squire(),
loginAction = jasmine.createSpy(),
mocks = {
'Magento_Customer/js/action/login': loginAction,
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy()
},
'Magento_Customer/js/model/authentication-popup': {
createPopUp: jasmine.createSpy(),
modalWindow: null
},
'Magento_Ui/js/modal/alert': jasmine.createSpy(),
'mage/url': jasmine.createSpyObj('customerData', ['setBaseUrl'])
},
obj;
loginAction.registerLoginCallback = jasmine.createSpy();
beforeEach(function (done) {
window.authenticationPopup = {
customerRegisterUrl: 'register_url',
customerForgotPasswordUrl: 'forgot_password_url',
autocomplete: 'autocomplete_flag',
baseUrl: 'base_url',
customerLoginUrl:'customer_login_url'
};
injector.mock(mocks);
injector.require(['Magento_Customer/js/view/authentication-popup'], function (Constr) {
obj = new Constr({
provider: 'provName',
name: '',
index: ''
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('Magento_Customer/js/view/authentication-popup', function () {
describe('"isActive" method', function () {
it('Check for return value.', function () {
mocks['Magento_Customer/js/customer-data'].get.and.returnValue(function () {
return true;
});
expect(obj.isActive()).toBeFalsy();
});
});
});
describe('Magento_Customer/js/view/authentication-popup', function () {
describe('"setModalElement" method', function () {
it('skips modal initialization when cart is not initialized', function () {
mocks['Magento_Customer/js/customer-data'].get.and.returnValue(
ko.observable({})
);
obj.setModalElement();
expect(
mocks['Magento_Customer/js/model/authentication-popup']
.createPopUp
).not.toHaveBeenCalled();
});
it('skips modal initialization when guest checkout is allowed', function () {
mocks['Magento_Customer/js/customer-data'].get.and.returnValue(
ko.observable({
isGuestCheckoutAllowed: true
})
);
obj.setModalElement();
expect(
mocks['Magento_Customer/js/model/authentication-popup']
.createPopUp
).not.toHaveBeenCalled();
});
it('initializes modal when guest checkout is disabled', function () {
mocks['Magento_Customer/js/customer-data'].get.and.returnValue(
ko.observable({
isGuestCheckoutAllowed: false
})
);
obj.setModalElement();
expect(
mocks['Magento_Customer/js/model/authentication-popup']
.createPopUp
).toHaveBeenCalled();
});
});
});
describe('Magento_Customer/js/view/authentication-popup', function () {
describe('"login" method', function () {
it('Check for return value.', function () {
var event = {
currentTarget: '<form><input type="text" name="username" value="customer"/></form>',
stopPropagation: jasmine.createSpy()
};
expect(obj.login(null, event)).toBeFalsy();
expect(mocks['Magento_Customer/js/action/login']).toHaveBeenCalledWith({
username: 'customer',
customerLoginUrl: 'customer_login_url'
});
});
});
});
});
@@ -0,0 +1,251 @@
/*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint-disable max-nested-callbacks*/
/*jscs:disable jsDoc*/
define([
'jquery',
'Magento_Directory/js/region-updater'
], function ($) {
'use strict';
var regionJson = {
'config': {
'show_all_regions': true,
'regions_required': [
'US'
]
},
'US':
[
{
'id': 1,
'code': 'AL',
'name': 'Alabama'
},
{
'id': 2,
'code': 'AK',
'name': 'Alaska'
},
{
'id': 3,
'code': 'AS',
'name': 'American Samoa'
}
],
'DE':
[
{
'id': 81,
'code': 'BAY',
'name': 'Bayern'
},
{
'id': 82,
'code': 'BER',
'name': 'Berlin'
},
{
'id': 83,
'code': 'BRG',
'name': 'Brandenburg'
}
]
},
defaultCountry = 'GB',
countries = {
'': '',
'US': 'United States',
'GB': 'United Kingdom',
'DE': 'Germany',
'IT': 'Italy'
},
regions = {
'': 'Please select a region, state or province.'
},
countryEl,
regionSelectEl,
regionInputEl,
postalCodeEl,
formEl,
containerEl;
function createFormField() {
var fieldWrapperEl = document.createElement('div'),
labelEl = document.createElement('label'),
inputControlEl = document.createElement('div'),
i;
fieldWrapperEl.appendChild(labelEl);
fieldWrapperEl.appendChild(inputControlEl);
for (i = 0; i < arguments.length; i++) {
inputControlEl.appendChild(arguments[i]);
}
labelEl.setAttribute('class', 'label');
fieldWrapperEl.setAttribute('class', 'field required');
inputControlEl.setAttribute('class', 'control');
return fieldWrapperEl;
}
function buildSelectOptions(select, options, defaultOption) {
var optionValue,
optionEl;
defaultOption = typeof defaultOption === 'undefined' ? '' : defaultOption;
// eslint-disable-next-line guard-for-in
for (optionValue in options) {
if (options.hasOwnProperty(optionValue)) {
optionEl = document.createElement('option');
optionEl.setAttribute('value', optionValue);
optionEl.textContent = countries[optionValue];
// eslint-disable-next-line max-depth
if (defaultOption === optionValue) {
optionEl.setAttribute('selected', 'selected');
}
select.add(optionEl);
}
}
}
function init(config) {
var defaultConfig = {
'optionalRegionAllowed': true,
'regionListId': '#' + regionSelectEl.id,
'regionInputId': '#' + regionInputEl.id,
'postcodeId': '#' + postalCodeEl.id,
'form': '#' + formEl.id,
'regionJson': regionJson,
'defaultRegion': 0,
'countriesWithOptionalZip': ['GB']
};
$(countryEl).directoryRegionUpdater($.extend({}, defaultConfig, config || {}));
}
beforeEach(function () {
containerEl = document.createElement('div');
formEl = document.createElement('form');
regionSelectEl = document.createElement('select');
regionInputEl = document.createElement('input');
postalCodeEl = document.createElement('input');
countryEl = document.createElement('select');
regionSelectEl.setAttribute('id', 'dir_region_id');
regionSelectEl.setAttribute('style', 'display:none;');
regionInputEl.setAttribute('id', 'dir_region');
regionInputEl.setAttribute('style', 'display:none;');
countryEl.setAttribute('id', 'dir_country');
postalCodeEl.setAttribute('id', 'zip');
formEl.setAttribute('id', 'dir_test_form');
formEl.appendChild(createFormField(countryEl));
formEl.appendChild(createFormField(regionSelectEl, regionInputEl));
formEl.appendChild(createFormField(postalCodeEl));
containerEl.appendChild(formEl);
buildSelectOptions(regionSelectEl, regions);
buildSelectOptions(countryEl, countries, defaultCountry);
document.body.appendChild(containerEl);
});
afterEach(function () {
$(containerEl).remove();
formEl = undefined;
containerEl = undefined;
regionSelectEl = undefined;
regionInputEl = undefined;
postalCodeEl = undefined;
countryEl = undefined;
});
describe('Magento_Directory/js/region-updater', function () {
it('Check that default country is selected', function () {
init();
expect($(countryEl).val()).toBe(defaultCountry);
});
it('Check that region list is not displayed when selected country has no predefined regions', function () {
init();
$(countryEl).val('GB').trigger('change');
expect($(regionInputEl).is(':visible')).toBe(true);
expect($(regionInputEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).is(':visible')).toBe(false);
expect($(regionSelectEl).is(':disabled')).toBe(true);
});
it('Check country that has predefined and optional regions', function () {
init();
$(countryEl).val('DE').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(true);
expect($(regionSelectEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).hasClass('required-entry')).toBe(false);
expect($(regionInputEl).is(':visible')).toBe(false);
expect(
$(regionSelectEl).find('option')
.map(function () {
return this.textContent;
})
.get()
).toContain('Berlin');
});
it('Check country that has predefined and required regions', function () {
init();
$(countryEl).val('US').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(true);
expect($(regionSelectEl).is(':disabled')).toBe(false);
expect($(regionSelectEl).hasClass('required-entry')).toBe(true);
expect($(regionInputEl).is(':visible')).toBe(false);
expect(
$(regionSelectEl).find('option')
.map(function () {
return this.textContent;
})
.get()
).toContain('Alaska');
});
it('Check that region fields are not displayed for country with optional regions if configured', function () {
init({
optionalRegionAllowed: false
});
$(countryEl).val('DE').trigger('change');
expect($(regionSelectEl).is(':visible')).toBe(false);
expect($(regionInputEl).is(':visible')).toBe(false);
});
it('Check that initial values are not overwritten - region input', function () {
$(countryEl).val('GB');
$(regionInputEl).val('Liverpool');
$(postalCodeEl).val('L13 0AL');
init();
expect($(countryEl).val()).toBe('GB');
expect($(regionInputEl).val()).toBe('Liverpool');
expect($(postalCodeEl).val()).toBe('L13 0AL');
});
it('Check that initial values are not overwritten - region select', function () {
$(countryEl).val('US');
$(postalCodeEl).val('99501');
init({
defaultRegion: '2'
});
expect($(countryEl).val()).toBe('US');
expect($(regionSelectEl).find('option:selected').text()).toBe('Alaska');
expect($(postalCodeEl).val()).toBe('99501');
});
it('Check that region values are cleared out on country change - region input', function () {
$(countryEl).val('GB');
$(regionInputEl).val('Liverpool');
init();
$(countryEl).val('IT').trigger('change');
expect($(countryEl).val()).toBe('IT');
expect($(regionInputEl).val()).toBe('');
});
it('Check that region values are cleared out on country change - region select', function () {
$(countryEl).val('US');
init({
defaultRegion: '2'
});
$(countryEl).val('DE').trigger('change');
expect($(countryEl).val()).toBe('DE');
expect($(regionSelectEl).val()).toBe('');
});
});
});
@@ -0,0 +1,107 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire',
'ko',
'jquery',
'mage/validation'
], function (Squire, ko, $) {
'use strict';
var injector = new Squire(),
customerDataMock = ko.observable({}),
mocks = {
'Magento_Customer/js/customer-data': {
/**
* Return customer data mock.
* @return {*}
*/
get: function () {
return customerDataMock;
}
},
'Magento_Ui/js/modal/confirm': jasmine.createSpy()
},
obj;
describe('Magento_InstantPurchase/js/view/instant-purchase', function () {
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['Magento_InstantPurchase/js/view/instant-purchase'], function (Constr) {
obj = Constr({
index: 'purchase'
});
done();
});
$('body').append('<div id="product_addtocart_form"></div>');
});
afterEach(function () {
$('#product_addtocart_form').remove();
try {
injector.clean();
injector.remove();
} catch (e) {}
});
it('Check initialized data.', function () {
expect(obj.showButton()).toBeFalsy();
expect(obj.paymentToken()).toBeFalsy();
expect(obj.shippingAddress()).toBeFalsy();
expect(obj.billingAddress()).toBeFalsy();
expect(obj.shippingMethod()).toBeFalsy();
});
it('Check when customer data exists.', function () {
var dataStub = {
available: true,
paymentToken: 'paymentToken',
shippingAddress: 'shippingAddress',
billingAddress: 'billingAddress',
shippingMethod: 'shippingMethod'
};
customerDataMock(dataStub);
expect(obj.showButton()).toBe(dataStub.available);
expect(obj.paymentToken()).toBe(dataStub.paymentToken);
expect(obj.shippingAddress()).toBe(dataStub.shippingAddress);
expect(obj.billingAddress()).toBe(dataStub.billingAddress);
expect(obj.shippingMethod()).toBe(dataStub.shippingMethod);
});
it('Check "setPurchaseData".', function () {
var dataStub = {
available: true,
paymentToken: 'paymentToken',
shippingAddress: 'shippingAddress',
billingAddress: 'billingAddress',
shippingMethod: 'shippingMethod'
};
obj.setPurchaseData(dataStub);
expect(obj.showButton()).toBe(dataStub.available);
expect(obj.paymentToken()).toBe(dataStub.paymentToken);
expect(obj.shippingAddress()).toBe(dataStub.shippingAddress);
expect(obj.billingAddress()).toBe(dataStub.billingAddress);
expect(obj.shippingMethod()).toBe(dataStub.shippingMethod);
});
it('Check "instantPurchase" with failed validation.', function () {
spyOn(jQuery.fn, 'valid').and.returnValue(false);
expect(obj.instantPurchase()).toBeUndefined();
expect(mocks['Magento_Ui/js/modal/confirm']).not.toHaveBeenCalled();
});
it('Check "instantPurchase" with success validation.', function () {
spyOn(jQuery.fn, 'valid').and.returnValue(true);
expect(obj.instantPurchase()).toBeUndefined();
expect(mocks['Magento_Ui/js/modal/confirm']).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,78 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'Magento_MediaGalleryUi/js/grid/messages',
'escaper'
], function (Messages, Escaper) {
'use strict';
describe('Magento_MediaGalleryUi/js/grid/messages', function () {
var messagesInstance,
escaperInstance,
messageText,
errorType,
successType;
beforeEach(function () {
escaperInstance = Escaper;
messagesInstance = Messages({
escaper: escaperInstance
});
messageText = 'test message';
errorType = 'error';
successType = 'success';
});
it('add error message, get error message', function () {
messagesInstance.add(errorType, messageText);
expect(JSON.stringify(messagesInstance.get())).toEqual(JSON.stringify([{
code: errorType,
message: messageText
}]));
});
it('add success message, get success message', function () {
messagesInstance.add(successType, messageText);
expect(JSON.stringify(messagesInstance.get())).toEqual(JSON.stringify([{
code: successType,
message: messageText
}]));
});
it('handles multiple messages', function () {
messagesInstance.add(successType, messageText);
messagesInstance.add(errorType, messageText);
expect(JSON.stringify(messagesInstance.get())).toEqual(JSON.stringify([
{
code: successType,
message: messageText
},
{
code: errorType,
message: messageText
}
]));
});
it('cleans messages', function () {
messagesInstance.add(errorType, messageText);
messagesInstance.clear();
expect(JSON.stringify(messagesInstance.get())).toEqual(JSON.stringify([]));
});
it('prepare message to be rendered as HTML', function () {
var escapedMessage = 'escaped message';
// eslint-disable-next-line max-nested-callbacks
escaperInstance.escapeHtml = jasmine.createSpy().and.callFake(function () {
return escapedMessage;
});
expect(messagesInstance.prepareMessageUnsanitizedHtml(messageText)).toEqual(escapedMessage);
});
});
});
@@ -0,0 +1,47 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_Msrp/js/msrp'
], function ($) {
'use strict';
describe('Testing addToCart Widget', function () {
var wdContainer;
beforeEach(function () {
wdContainer = $('<div />');
});
afterEach(function () {
$(wdContainer).remove();
});
it('widget extends jQuery object', function () {
expect($.fn.addToCart).toBeDefined();
});
it('widget gets options', function () {
wdContainer.addToCart({
'cartButtonId': 'FAKE_ID'
});
expect(wdContainer.addToCart('option', 'cartButtonId')).toBe('FAKE_ID');
});
it('widget tries to submit Cart Form on click', function (done) {
var link = $('<a />');
wdContainer.addToCart({
'cartButtonId': link
}).on('addToCart', function (event, result) {
expect(result).toEqual(wdContainer[0]);
done();
});
link.trigger('click');
});
});
});
@@ -0,0 +1,67 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(['squire', 'jquery'], function (Squire, $) {
'use strict';
var injector = new Squire(),
dataPost = {
postData: jasmine.createSpy()
},
mocks = {
/** Stub */
'mage/dataPost': function () {
return dataPost;
}
},
checkbox,
url = 'example.com',
/**
* Toggle checkbox and assert that event was triggered.
*
* @param {Integer} value
*/
toggleCheckbox = function (value) {
checkbox.trigger('click');
expect(dataPost.postData.calls.mostRecent().args[0]).toEqual({
action: url,
data: {
useBalance: value
}
});
};
beforeEach(function (done) {
checkbox = $('<input type="checkbox" name="use_balance" checked="checked"/>');
$(document.body).append(checkbox);
injector.mock(mocks);
injector.require(['multiShippingBalance'], function (balance) {
balance({
changeUrl: url
}, checkbox);
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
checkbox.remove();
});
describe('multiShippingBalance', function () {
it('Check actions after clicking on checkbox.', function () {
toggleCheckbox(0);
toggleCheckbox(1);
toggleCheckbox(0);
expect(dataPost.postData).toHaveBeenCalledTimes(3);
});
});
});
@@ -0,0 +1,119 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire',
'jquery',
'ko',
'multiShipping'
], function (Squire, $, ko, MultiShipping) {
'use strict';
describe('Magento_Multishipping/js/multi-shipping', function () {
var injector = new Squire(),
Obj;
describe('Check Cart data preparation process', function () {
var customerData = ko.observable({}),
mocks = {
'Magento_Customer/js/customer-data': {
get: jasmine.createSpy('get', function () {
return customerData;
}).and.callThrough(),
reload: jasmine.createSpy()
}
},
summaryCount = {};
beforeEach(function (done) {
injector.mock(mocks);
injector.require(['multiShipping'], function (Instance) {
Obj = Instance;
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
customerData({});
});
it('Prepare Cart data with the same items qty', function () {
summaryCount['summary_count'] = 0;
customerData(summaryCount);
new Obj({});
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].reload).not.toHaveBeenCalled();
});
it('Prepare Cart data with different items qty', function () {
summaryCount['summary_count'] = 1;
customerData(summaryCount);
new Obj({});
expect(mocks['Magento_Customer/js/customer-data'].get).toHaveBeenCalledWith('cart');
expect(mocks['Magento_Customer/js/customer-data'].reload).toHaveBeenCalledWith(['cart'], false);
});
});
describe('Check Multishipping events', function () {
var addNewAddressBtn,
addressflag,
canContinueBtn,
canContinueFlag,
originalGetJSON;
beforeEach(function () {
originalGetJSON = $.getJSON;
addNewAddressBtn = $('<button type="button" data-role="add-new-address"/>');
addressflag = $('<input type="hidden" value="0" id="add_new_address_flag"/>');
canContinueBtn = $('<button type="submit" data-role="can-continue" data-flag="1"/>');
canContinueFlag = $('<input type="hidden" value="0" id="can_continue_flag"/>');
$(document.body).append(addNewAddressBtn)
.append(addressflag)
.append(canContinueBtn)
.append(canContinueFlag);
$.getJSON = jasmine.createSpy().and.callFake(function () {
var deferred = $.Deferred();
return deferred.promise();
});
});
afterEach(function () {
addNewAddressBtn.remove();
addressflag.remove();
canContinueBtn.remove();
canContinueFlag.remove();
$.getJSON = originalGetJSON;
});
it('Check add new address event', function () {
Obj = new MultiShipping({});
Obj.element = jasmine.createSpyObj('element', ['submit']);
addNewAddressBtn.trigger('click');
expect(Obj.element.submit).toHaveBeenCalled();
expect(addressflag.val()).toBe('1');
});
it('Check can continue event', function () {
Obj = new MultiShipping({});
Obj.element = jasmine.createSpyObj('element', ['submit']);
canContinueBtn.trigger('click');
expect(Obj.element.submit).not.toHaveBeenCalled();
expect(canContinueFlag.val()).toBe('1');
});
});
});
});
@@ -0,0 +1,141 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'squire',
'ko',
'jquery',
'mage/validation'
], function (Squire, ko, $) {
'use strict';
var injector = new Squire(),
obj,
checkbox,
emailElem,
button,
response = ko.observable({}),
resolverMock = jasmine.createSpy('subscription-status-resolver', function (email, deferred) {
if (response().errors) {
deferred.reject();
} else {
deferred.resolve(response().subscribed);
}
}).and.callThrough(),
mocks = {
'Magento_Newsletter/js/subscription-status-resolver': resolverMock
};
beforeEach(function (done) {
checkbox = $('<input type="checkbox" class="checkbox" name="is_subscribed" id="is_subscribed"/>');
emailElem = $('<input type="email" name="email" id="email_address"/>');
button = $('<button type="submit" id="button"/>');
$(document.body).append(checkbox).append(emailElem).append(button);
injector.mock(mocks);
injector.require(['Magento_Newsletter/js/newsletter-sign-up'], function (Constr) {
obj = new Constr({
submitButton: '#button',
signUpElement: '#is_subscribed'
}, '#email_address');
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
checkbox.remove();
emailElem.remove();
button.remove();
});
describe('Magento_Newsletter/js/newsletter-sign-up', function () {
it('Check for properties defined', function () {
expect(obj.hasOwnProperty('submitButton')).toBeDefined();
expect(typeof obj.submitButton).toEqual('string');
expect(obj.hasOwnProperty('signUpElement')).toBeDefined();
expect(typeof obj.signUpElement).toEqual('string');
expect(obj.hasOwnProperty('element')).toBeDefined();
expect(typeof obj.element).toEqual('string');
});
it('Check sign-up process when Subscription is checked', function () {
emailElem.val('email@example.com');
checkbox.prop('checked', true);
obj.updateSignUpStatus();
expect(resolverMock).not.toHaveBeenCalled();
expect(button.is(':disabled')).toBeFalsy();
expect(checkbox.is(':checked')).toBeTruthy();
});
it('Check sign-up process without email', function () {
checkbox.prop('checked', false);
obj.updateSignUpStatus();
expect(resolverMock).not.toHaveBeenCalled();
expect(checkbox.is(':checked')).toBeFalsy();
});
it('Check sign-up process with incorrect email', function () {
emailElem.val('emailexample.com');
checkbox.prop('checked', false);
obj.updateSignUpStatus();
expect(resolverMock).not.toHaveBeenCalled();
expect(checkbox.is(':checked')).toBeFalsy();
});
it('Check Subscription with correct data', function () {
response({
subscribed: true,
errors: false
});
emailElem.val('email@example.com');
checkbox.prop('checked', false);
obj.updateSignUpStatus();
expect(resolverMock).toHaveBeenCalled();
expect(checkbox.is(':checked')).toBeTruthy();
expect(button.is(':disabled')).toBeFalsy();
});
it('Check sign-up process with non-subscribed email', function () {
response({
subscribed: false,
errors: false
});
emailElem.val('email@example.com');
checkbox.prop('checked', false);
obj.updateSignUpStatus();
expect(resolverMock).toHaveBeenCalled();
expect(checkbox.is(':checked')).toBeFalsy();
});
it('Check sign-up process with errors', function () {
response({
subscribed: true,
errors: true
});
emailElem.val('email@example.com');
checkbox.prop('checked', false);
obj.updateSignUpStatus();
expect(resolverMock).toHaveBeenCalled();
expect(checkbox.is(':checked')).toBeFalsy();
});
});
});
@@ -0,0 +1,65 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_PageCache/js/form-key-provider'
], function ($, formKeyInit) {
'use strict';
describe('Testing FormKey Provider', function () {
var inputContainer;
function getFormKeyCookie() {
var nameEQ = 'form_key=',
cookieArr = document.cookie.split(';');
return cookieArr[0].split(nameEQ)[1];
}
beforeEach(function () {
inputContainer = document.createElement('input');
inputContainer.setAttribute('value', '');
inputContainer.setAttribute('name', 'form_key');
document.querySelector('body').appendChild(inputContainer);
});
afterEach(function () {
$(inputContainer).remove();
document.cookie = 'form_key= ; expires = Thu, 01 Jan 1970 00:00:00 GMT';
});
it('sets value of input[form_key]', function () {
var expires,
date = new Date();
date.setTime(date.getTime() + 86400000);
expires = '; expires=' + date.toUTCString();
document.cookie = 'form_key=FAKE_COOKIE' + expires + '; path=/';
formKeyInit({'isPaginationCacheEnabled': 0});
expect($(inputContainer).val()).toEqual('FAKE_COOKIE');
});
it('widget sets value to input[form_key] in case it empty', function () {
document.cookie = 'form_key= ; expires = Thu, 01 Jan 1970 00:00:00 GMT';
formKeyInit({'isPaginationCacheEnabled': 0});
expect($(inputContainer).val()).toEqual(jasmine.any(String));
expect($(inputContainer).val().length).toEqual(16);
});
it('widget gets value from input[form_key] in case cookie is empty is pagination cache enabled', function () {
var formKey = 'TestInputStrings';
document.cookie = 'form_key= ; expires = Thu, 01 Jan 1970 00:00:00 GMT';
$(inputContainer).val(formKey);
formKeyInit({'isPaginationCacheEnabled': 1});
expect($(inputContainer).val()).toEqual(jasmine.any(String));
expect($(inputContainer).val().length).toEqual(16);
expect(formKey).toEqual(getFormKeyCookie());
});
});
});
@@ -0,0 +1,226 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'Magento_PageCache/js/page-cache'
], function ($) {
'use strict';
describe('Testing html-comments-parser $.fn.comments behavior', function () {
var element,
iframe,
comment,
host;
beforeEach(function () {
element = $('<div />');
iframe = $('<iframe />');
comment = '<!--COMMENT CONTENT-->';
host = window.location.hostname;
$('body')
.append(element)
.append(iframe);
});
afterEach(function () {
$(element).remove();
$(iframe).remove();
});
it('comments fn exists', function () {
expect($.fn.comments).toBeDefined();
expect($.fn.comments()).toEqual([]);
});
it('on empty node comments() returns empty Array', function () {
expect($(element).comments()).toEqual([]);
expect($(iframe).insertAfter('body').comments()).toEqual([]);
});
it('on non-empty node comments() returns empty Array with nodes', function () {
element.html(comment);
expect($(element).comments().length).toEqual(1);
expect($(element).comments()[0].nodeType).toEqual(8);
expect($(element).comments()[0].nodeValue).toEqual('COMMENT CONTENT');
});
it('on iframe from same host returns Array with nodes', function () {
iframe.contents().find('body').html(comment);
iframe.attr('src', '//' + host + '/');
expect(iframe.comments().length).toEqual(1);
expect(iframe.comments()[0].nodeType).toEqual(8);
expect(iframe.comments()[0].nodeValue).toEqual('COMMENT CONTENT');
});
it('on iframe from other host returns empty Array', function () {
iframe.contents().find('body').html(comment);
iframe.attr('src', '//' + host + '.otherHost/?origin_url=' + host);
expect(iframe.comments().length).toEqual(0);
});
});
describe('Testing FormKey Widget', function () {
var wdContainer, inputContainer;
beforeEach(function () {
wdContainer = $('<div />');
inputContainer = $('<input />');
});
afterEach(function () {
$(wdContainer).remove();
$(inputContainer).remove();
});
it('widget extends jQuery object', function () {
expect($.fn.formKey).toBeDefined();
});
it('widget gets value of input[form_key]', function () {
spyOn($.mage.cookies, 'get').and.returnValue('FAKE_COOKIE');
wdContainer.formKey({
'inputSelector': inputContainer
});
expect($.mage.cookies.get).toHaveBeenCalled();
expect(inputContainer.val()).toBe('FAKE_COOKIE');
});
it('widget sets value to input[form_key] in case it empty', function () {
spyOn($.mage.cookies, 'set');
spyOn($.mage.cookies, 'get');
wdContainer.formKey({
'inputSelector': inputContainer
});
expect($.mage.cookies.get).toHaveBeenCalled();
expect($.mage.cookies.set).toHaveBeenCalled();
expect(inputContainer.val()).toEqual(jasmine.any(String));
});
});
describe('Testing PageCache Widget', function () {
var wdContainer, pageBlockContainer;
beforeEach(function () {
wdContainer = $('<div />');
pageBlockContainer = $('<div />');
});
afterEach(function () {
$(wdContainer).remove();
$(pageBlockContainer).remove();
});
it('widget extends jQuery object', function () {
expect($.fn.pageCache).toBeDefined();
});
it('widget breaks if no private_content_version cookie', function () {
spyOn($.mage.cookies, 'get');
spyOn($.fn, 'comments');
wdContainer.pageCache();
expect($.mage.cookies.get).toHaveBeenCalled();
expect($.fn.comments).not.toHaveBeenCalled();
});
it('_searchPlaceholders is called only when HTML_COMMENTS', function () {
var nodes;
spyOn($.mage.cookies, 'get').and.returnValue('FAKE_VERSION_COOKIE');
spyOn($.mage.pageCache.prototype, '_searchPlaceholders');
wdContainer
.html('<!-- BLOCK FAKE_BLOCK -->FAKE_TEXT<!-- /BLOCK FAKE_BLOCK -->')
.pageCache();
nodes = wdContainer.comments();
expect(nodes.length).toEqual(2);
expect($.mage.cookies.get).toHaveBeenCalled();
expect($.mage.pageCache.prototype._searchPlaceholders).toHaveBeenCalled();
expect($.mage.pageCache.prototype._searchPlaceholders).toHaveBeenCalledWith(nodes);
});
it('_searchPlaceholders returns Array of blocks', function () {
var nodes,
searches;
spyOn($.mage.cookies, 'get').and.returnValue('FAKE_VERSION_COOKIE');
wdContainer
.html('<!-- BLOCK FAKE_BLOCK -->FAKE_TEXT<!-- /BLOCK FAKE_BLOCK -->')
.pageCache();
nodes = wdContainer.comments();
searches = wdContainer.data('magePageCache')._searchPlaceholders(nodes);
expect(wdContainer.data('magePageCache')._searchPlaceholders()).toEqual([]);
expect(searches[0]).toEqual(jasmine.objectContaining({
name: 'FAKE_BLOCK'
}));
expect(searches[0].openElement.nodeType).toBeDefined();
expect(searches[0].closeElement.nodeType).toBeDefined();
});
it('_replacePlaceholder appends HTML after sibling node', function () {
var replacer,
searcher,
placeholders,
context;
context = {
options: {
patternPlaceholderOpen: /^ BLOCK (.+) $/,
patternPlaceholderClose: /^ \/BLOCK (.+) $/
}
};
// eslint-disable-next-line jquery-no-bind-unbind
replacer = $.mage.pageCache.prototype._replacePlaceholder.bind(context);
// eslint-disable-next-line jquery-no-bind-unbind
searcher = $.mage.pageCache.prototype._searchPlaceholders.bind(context);
wdContainer
.html('<span></span><!-- BLOCK FAKE_BLOCK -->FAKE_TEXT<!-- /BLOCK FAKE_BLOCK -->');
placeholders = searcher(wdContainer.comments());
replacer(placeholders[0], '<span>FAKE_HTML</span>');
expect(wdContainer.html()).toEqual('<span></span><span>FAKE_HTML</span>');
});
it('_replacePlaceholder prepends HTML if no sibling', function () {
var replacer,
searcher,
placeholders,
context;
context = {
options: {
patternPlaceholderOpen: /^ BLOCK (.+) $/,
patternPlaceholderClose: /^ \/BLOCK (.+) $/
}
};
// eslint-disable-next-line jquery-no-bind-unbind
replacer = $.mage.pageCache.prototype._replacePlaceholder.bind(context);
// eslint-disable-next-line jquery-no-bind-unbind
searcher = $.mage.pageCache.prototype._searchPlaceholders.bind(context);
wdContainer
.html('<!-- BLOCK FAKE_BLOCK -->FAKE_TEXT<!-- /BLOCK FAKE_BLOCK -->');
placeholders = searcher(wdContainer.comments());
replacer(placeholders[0], '<span>FAKE_HTML</span>');
expect(wdContainer.html()).toEqual('<span>FAKE_HTML</span>');
});
});
});
@@ -0,0 +1,84 @@
/*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint-disable max-nested-callbacks*/
/*jscs:disable jsDoc*/
define([
'jquery',
'jquery/validate',
'Magento_Payment/js/transparent'
], function ($) {
'use strict';
var containerEl,
formEl,
jQueryAjax;
function init(config) {
var defaultConfig = {
orderSaveUrl: '/',
gateway: 'payflowpro',
editFormSelector: '#' + formEl.id
};
$(formEl).find(':radio[value="payflowpro"]').prop('checked', 'checked');
$(formEl).transparent($.extend({}, defaultConfig, config || {}));
}
beforeEach(function () {
if (!window.FORM_KEY) {
window.FORM_KEY = '61d0c9da0aa473d214f61913967cc0ea';
}
$('<div id="admin_edit_order_form_container">' +
'<form id="admin_edit_order_form" action="/">' +
'<input type="radio" name="payment[method]" value="payflowpro"/>' +
'<input type="radio" name="payment[method]" value="money_order"/>' +
'</form>' +
'</div>'
).appendTo(document.body);
containerEl = document.getElementById('admin_edit_order_form_container');
formEl = document.getElementById('admin_edit_order_form');
jQueryAjax = $.ajax;
});
afterEach(function () {
$(containerEl).remove();
formEl = undefined;
containerEl = undefined;
$.ajax = jQueryAjax;
jQueryAjax = undefined;
});
describe('Magento_Payment/js/transparent', function () {
describe('beforeSubmitOrder handler', function () {
it('is registered when selected payment method requires transparent', function () {
init();
expect(($._data(formEl, 'events') || {}).beforeSubmitOrder[0].type).toBe('beforeSubmitOrder');
expect(($._data(formEl, 'events') || {}).beforeSubmitOrder[0].namespace).toBe('payflowpro');
});
it('is not registered when selected payment method does not require transparent', function () {
init();
$(formEl).find(':radio[value="money_order"]').prop('checked', 'checked');
$(formEl).trigger('changePaymentMethod', ['money_order']);
expect(($._data(formEl, 'events') || {}).beforeSubmitOrder).toBeUndefined();
});
it('returns false to prevent normal order creation', function () {
var beforeSubmitOrderEvent;
$.ajax = jasmine.createSpy();
init({
orderSaveUrl: '/admin/paypal/transparent/requestSecureToken'
});
beforeSubmitOrderEvent = $.Event('beforeSubmitOrder');
$(formEl).trigger(beforeSubmitOrderEvent);
expect($.ajax).toHaveBeenCalledWith(jasmine.objectContaining({
url: '/admin/paypal/transparent/requestSecureToken',
type: 'post'
}));
expect(beforeSubmitOrderEvent.result).toBe(false);
expect(beforeSubmitOrderEvent.isImmediatePropagationStopped()).toBe(true);
});
});
});
});
@@ -0,0 +1,24 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/validate',
'Magento_Payment/js/model/credit-card-validation/validator'
], function ($) {
'use strict';
describe('Magento_Payment/js/model/credit-card-validation/validator', function () {
it('Check credit card expiration year validator.', function () {
var year = new Date().getFullYear();
expect($.validator.methods['validate-card-year']('1234')).toBeFalsy();
expect($.validator.methods['validate-card-year']('')).toBeFalsy();
expect($.validator.methods['validate-card-year']((year - 1).toString())).toBeFalsy();
expect($.validator.methods['validate-card-year']((year + 1).toString())).toBeTruthy();
});
});
});
@@ -0,0 +1,78 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'squire',
'ko',
'jquery',
'uiComponent'
], function (Squire, ko, $, Component) {
'use strict';
describe('paypal/js/view/payment/method-renderer/paypal-express-abstract', function () {
var injector = new Squire(),
mocks = {
'Magento_Paypal/js/action/set-payment-method': jasmine.createSpy(),
'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract': Component,
'Magento_Checkout/js/model/quote': {
billingAddress: ko.observable(),
shippingAddress: ko.observable(),
paymentMethod: ko.observable()
},
'Magento_Checkout/js/model/payment/additional-validators': {
validate: jasmine.createSpy().and.returnValue(true)
},
'Magento_Paypal/js/in-context/express-checkout-smart-buttons': jasmine.createSpy(),
'Magento_Customer/js/customer-data': {
invalidate: jasmine.createSpy()
}
},
obj;
beforeAll(function (done) {
window.checkoutConfig = {
quoteData: {
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
entity_Id: 1
},
formKey: 'formKey'
};
window.customerData = {
id: 1
};
injector.mock(mocks);
injector.require(
['Magento_Paypal/js/view/payment/method-renderer/in-context/checkout-express'],
function (Constr) {
obj = new Constr({
provider: 'provName',
name: 'test',
index: 'test',
item: {
method: 'payflow_express_bml'
},
clientConfig: {}
});
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
describe('check smart button initialization', function () {
it('express-checkout-smart-buttons is initialized', function () {
obj.renderPayPalButtons();
expect(mocks['Magento_Paypal/js/in-context/express-checkout-smart-buttons']).toHaveBeenCalled();
});
});
});
});
@@ -0,0 +1,143 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'squire',
'ko',
'mage/translate'
], function ($, Squire, ko, $t) {
'use strict';
window.$t = $t;
describe('paypal/js/view/payment/method-renderer/paypal-express-abstract', function () {
var injector = new Squire(),
successPromise = jasmine.createSpyObj('successPromise', ['done']),
setPaymentMock = jasmine.createSpy('set-payment-information', function () {
return successPromise;
}).and.callThrough(),
validateMock = jasmine.createSpy('validate', function () {
return true;
}).and.callThrough(),
mocks = {
'Magento_Checkout/js/model/checkout-data-resolver': {
/** Stub */
applyBillingAddress: function () {
return true;
},
/** Stub */
resolveBillingAddress: function () {
return true;
}
},
'Magento_Checkout/js/model/quote': {
billingAddress: ko.observable(),
shippingAddress: ko.observable(),
paymentMethod: ko.observable(),
totals: ko.observable({}),
/** Stub */
isVirtual: function () {
return false;
}
},
'Magento_Checkout/js/action/set-payment-information': setPaymentMock,
'Magento_Checkout/js/model/payment/additional-validators': {
validate: validateMock
}
},
paypalExpressAbstract,
tplElement = $('<div data-bind="with: child"><div data-bind="template: getTemplate()"></div></div>')[0];
/**
* Click on PayPal help link and call expectation
* @param {Function} expectation
*/
function clickOnHelpLink(expectation) {
$('div.payment-method-title.field.choice > label > a > span').trigger('click');
expectation();
}
beforeAll(function (done) {
window.checkoutConfig = {
quoteData: {}
};
injector.mock(mocks);
injector.require(
['Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract'],
function (Constr) {
paypalExpressAbstract = new Constr({
isChecked: ko.observable(true),
provider: 'provName',
name: 'test',
index: 'test',
item: {
method: 'payflow_express_bml'
}
});
paypalExpressAbstract.child = paypalExpressAbstract;
$(document.body).append(tplElement);
ko.applyBindings(paypalExpressAbstract, tplElement);
done();
});
});
afterEach(function () {
try {
injector.clean();
injector.remove();
} catch (e) {}
});
it('showAcceptanceWindow is invoked when the anchor element of help link is clicked', function (done) {
spyOn(paypalExpressAbstract, 'showAcceptanceWindow');
setTimeout(function () {
clickOnHelpLink(function () {
expect(paypalExpressAbstract.showAcceptanceWindow).toHaveBeenCalled();
});
done();
}, 500);
});
it('Help link should be available in showAcceptanceWindow function', function (done) {
spyOn(window, 'open');
setTimeout(function () {
clickOnHelpLink(function () {
expect(window.open).toHaveBeenCalledWith(
jasmine.stringMatching('http'),
jasmine.anything(),
jasmine.anything()
);
});
done();
}, 500);
});
it('setPaymentMethodAction is called before redirect to paypal', function () {
paypalExpressAbstract.continueToPayPal();
expect(validateMock).toHaveBeenCalled();
expect(validateMock.calls.mostRecent()).toEqual(jasmine.objectContaining({
object: mocks['Magento_Checkout/js/model/payment/additional-validators'],
args: [],
returnValue: true
}));
expect(setPaymentMock).toHaveBeenCalled();
expect(setPaymentMock.calls.mostRecent()).toEqual(jasmine.objectContaining({
returnValue: successPromise
}));
expect(successPromise.done).toHaveBeenCalledWith(jasmine.any(Function));
});
afterAll(function (done) {
tplElement.remove();
done();
});
});
});

Some files were not shown because too many files have changed in this diff Show More