How Can I Test Image-Requiring Styled Components in Mocha? - mocha.js

I have a Styled Component that uses a require-d image file:
<MenuIcon src={require("../styles/menu-icon.png")}/>
Doing this (ie. passing a require-ed image file) is a standard pattern in Styled Components ... but obviously it makes for invalid JS.
As a result, when I try to test that component, I get:
/home/me/project/src/styles/menu-icon.png:1 SyntaxError: Invalid or
SyntaxError: Invalid or unexpected token
Jest apparently has a module name mapper that let's it solve this ... but I'm using Mocha, and as far as I can tell Mocha has no such resource.
So, my question is: in Mocha (without moduleNameMapper) how can I test a component that imports (requires) an image?

I found the answer in an issue thread for Ava (another test runner): https://issuehunt.io/r/avajs/ava/issues/2525
Basically you need to make a test-compiler.js file which tells require to just return null for non-JS extensions:
/**
* Disable webpack-specific features for tests, since tests do not use webpack
* to handle these
* #see https://issuehunt.io/r/avajs/ava/issues/2525
*/
require.extensions['.css'] = function () {
return null;
};
require.extensions['.png'] = function () {
return null;
};
require.extensions['.jpg'] = function () {
return null;
};
Then you just need to tell Mocha to require that file. You can use an argument when you run Mocha (-r test-compiler.js), or you can make a .mocharc.js file:
module.exports = {
exit: true,
require: ['jsdom-global/register', '#babel/register', './test-compiler.js' ],
spec: '!(node_modules)/**/*.spec.{js,cjs,mjs}',
};
The important part being this line:
require: ['jsdom-global/register', '#babel/register', './test-compiler.js' ],
which brings in other requirements (Babel and JS DOM) first, and then requires our test-compiler.js.

Related

Using pageBase with nightwatch.js

I'm trying to create an end-2-end test suite using nightwatch.js
I've looked around a bit and haven't really figured out how to use a pageBase, like is usually used when implementing POM.
I'm using the page_object that is built in to nightwatch, but can't seem to get it to use a pageBase.
Here is the code example.
To simplify things, let's say I have a common.js file, and a test.js file
I want test.js to inherit all of common.js commands and elements and implement some commands and elements of it's own, but I'm struggling with the syntax.
this is the common.js file
let commonCommands = {
clickOnMe: function () {
return this.waitForElementVisible('#someElement', 2000)
}
};
module.exports = {
commands: [commonCommands],
elements: {
someElement: '#elementId'
},
};
this is the test.js file
const common = require('./common');
let testCommands = {
doStuffFromTest: function () {
return this;
}
};
module.exports = {
url: function () {
return this.api.launch_url ;
},
commands: common.commands,
elements: common.elements
};
How can I add commands and elements to the test.js ?
You generally don't want to access those commands from your test, but rather from your other page objects. Since that's where all of your commands will be happening, common actions like clicking on an element or checking if something is present will be done at the page object level.

Jasmine Unit testing define library that was imported as a global variable

I have a project that uses pdfMake to generate a PDF. To use it I include the file in my index.html
<script src='js/pdfmake.js'></script>
<script src='js/vfs_fonts.js'></script>
Inside pdfmake.js it declares global["pdfMake"] which then allows me to use the library in my service.
pdfService:
pdfMake.createPdf(docDefinition).download(fileName);
Everything works great but when I tried to test ths method in my service I get an error that the test can't find the variable pdfMake. That makes sense considering it's loaded by index.html.
How can I replace this library with a mock in my test?
I've tried using a spy but since makePdf isn't a function that doesn't work. spyOn(service, 'makePdf').
I tried just setting it as a variable but that also didn't work and I get: Strict mode forbids implicit creation of global property 'pdfMake'
pdfMake = {
createPdf: jasmine.createSpy('createPdf').and.returnValue({
download: jasmine.createSpy('download')
}
}
I got the same problem and solved inserting the pdfMake mock on global variable window inside the unit test. So, in your case will be something like this:
window.pdfMake = {
createPdf: jasmine.createSpy('createPdf')
.and.returnValue({
download: jasmine.createSpy('download')
}),
};
I just fixed this issue by making below changes-
Declare pdfMake variable globally in your .ts file like-
declare var pdfMake;
And then mock the pdfMake function in your .spec file like this-
window['pdfMake'] = {
createPdf: function (param) {
return {
open: function () {
return true;
},
download: function () {
return true;
}
};
}
};

Problems with defining modules using AMD in Mocha

While writing tests I got bug TypeError: $.extend is not a function on toastr plugin that we are using. It seems that jQuery is not picked up properly, even tho is working normally in browser.
In our main mock file we imported jQuery and bind it to global windows object and it's accessible across whole application (but toastr plugin), even while testing in mocha:
import jsdom from 'jsdom';
import $ from 'jquery';
import chai from 'chai';
import chaiImmutable from 'chai-immutable';
import React from 'react';
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
const win = doc.defaultView;
global.document = doc;
global.window = win;
global.expect = chai.expect;
global.$ = $(win);
global.jquery = $(win);
global.jQuery = $(win);
Object.keys(window).forEach((key) => {
if (!(key in global)) {
global[key] = window[key];
}
});
chai.use(chaiImmutable);
So while taking closer look at toastr I noticed this:
; (function (define) {
define(['jquery'], function ($) {
// this function is called on inizialization
function getOptions() {
return $.extend({}, getDefaults(), toastr.options);
}
It takes jquery from node_modules directly and then defines object $ in function scope, that means that it's ignoring window.$ (which is working normally even in here).
Therefore logging $ will return function, and logging $.anyMethodFromjQuery ($.extend) will return undefined.
In the end I tried logging $.prototype, in the browser it will return me jQuery object while in mocha it returns empty object {}
So in the end it define didn't created prototype in mocha environment and I cannot add one line of code $ = window.$; in plugin, since no one should edit a plugin + we are using npm.
Is there any solution for this?
You're running into trouble because you are loading code that should be loaded by JSDom outside of it. While it is possible in some cases to load code in Node and then pass it to the window that JSDom creates, that's a brittle approach, as you've discovered. Whenever I use JSDom for things other than write-and-toss cases, I load every script that would normally be loaded by a browser through JSDom. This avoids running into the issue you ran into. Here's a proof-of-concept based on the code you've shown in the question. You'll see that toastr.getContainer() runs fine, because Toastr has been loaded by JSDom. If you try to use the same code with an import toastr from "toastr" you'll get the same problem you ran into.
import jsdom from 'jsdom';
import $ from 'jquery';
import path from "path";
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>', {
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"]
}
});
const win = doc.defaultView;
global.document = doc;
global.window = win;
global.$ = $(win);
global.jquery = $(win);
global.jQuery = $(win);
window.addEventListener("error", function () {
console.log("ERROR");
});
const script = document.createElement("script");
script.src = path.join(__dirname, "./node_modules/toastr/toastr.js");
document.head.appendChild(script);
// The load will necessarily be asynchronous, so we have to wait for it.
script.addEventListener("load", function () {
console.log("LOADED");
console.log(window.toastr);
// We do this here so that `toastr` is also picked up.
Object.keys(window).forEach((key) => {
if (!(key in global)) {
global[key] = window[key];
}
});
toastr.getContainer();
});
Note that the code hung when I tried calling toastr.info(...). I took a look at the code of Toastr but it is not clear to me what causes the problem. There are features of browsers that JSDom is unable to emulate. It is possible that Toastr is dependent on such features. In the past, I've sometimes had to switch test suites away from JSDom due to its limitations.

AngularJS testing error: Unknown provider: $_httpBackend_Provider <- $_httpBackend_

I am attempting to test an AngularJS controller with a Jasmine unit test spec file. My approach is to use $httpBacked, in the following test:
describe('SubmissionsController', function() {
var minimal_mock_response = [ { id: 1 } ];
var scope, routeParams, $httpBackend;
beforeEach(module('submissionServices'));
beforeEach(inject(function($_httpBackend_, $rootScope) {
scope = $rootScope.$new();
$httpBackend = $_httpBackend_;
$httpBackend.expectGET('/submissions').respond(minimal_mock_response);
routeParams = {};
}));
it('passes a trivial test', function() {
expect(true).toBe(true);
});
});
I inserted the expect(true).toBe(true) just to get the test to execute and fail, even though it does not touch the angular controller. When I I attempt to run the test with jasmine-headless-webkit, I receive the following error:
jasmine-headless-webkit spec/javascripts/SubmissionsControllerSpec.js
Running Jasmine specs...
F
FAIL: 1 test, 1 failure, 0.011 secs.
Submissions controllers SubmissionsController passes a trivial test. (XXX/spec/javascripts/SubmissionsControllerSpec.js:18)
Error: Unknown provider: $_httpBackend_Provider <- $_httpBackend_
Test ordering seed: --seed 9254
Are there any hints on how I can correct this error and make the trivial test execute?
Enclosing service names with underscores has some benefit.
From your code, I can see that you probably wanted to save the reference to $httpBackend. This is how you wanted to do. The placement of underscore was one off.
beforeEach(inject(function(_$httpBackend_, $rootScope) {
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
...
Angular is smart enough to remove underscores and returns $httpBackend back to you, and you can save it to your own $httpBackend.
I believe this is because you're injecting the wrong service. It doesn't know what $_httpBackend_ is. You should be able to just do this:
beforeEach(inject(function($httpBackend, $rootScope) {
scope = $rootScope.$new();
$httpBackend.expectGET('/submissions').respond(minimal_mock_response);
routeParams = {};
}));
If you want to get a reference to the $httpBackend service once and store that as $httpBackend, ghiden's answer is the way to go.

Is there a way to add a Jasmine matcher to the whole environment

There are plenty of documents that show how to add a matcher to a Jasmine spec (here, for example).
Has anyone found a way to add matchers to the whole environment; I'm wanting to create a set of useful matchers to be called by any and all tests, without copypasta all over my specs.
Currently working to reverse engineer the source, but would prefer a tried and true method, if one exists.
Sure, you just call beforeEach() without any spec scoping at all, and add matchers there.
This would globally add a toBeOfType matcher.
beforeEach(function() {
var matchers = {
toBeOfType: function(typeString) {
return typeof this.actual == typeString;
}
};
this.addMatchers(matchers);
});
describe('Thing', function() {
// matchers available here.
});
I've made a file named spec_helper.js full of things like custom matchers that I just need to load onto the page before I run the rest of the spec suite.
Here's one for jasmine 2.0+:
beforeEach(function(){
jasmine.addMatchers({
toEqualData: function() {
return {
compare: function(actual, expected) {
return { pass: angular.equals(actual, expected) };
}
};
}
});
});
Note that this uses angular's angular.equals.
Edit: I didn't know it was an internal implementation that may be subjected to change. Use at your own risk.
jasmine.Expectation.addCoreMatchers(matchers)
Based on previous answers, I created the following setup for angular-cli. I also need an external module in my matcher (in this case moment.js)
Note In this example I added an equalityTester, but it should work with a customer matcher
Create a file src/spec_helper.ts with the following contents:
// Import module
import { Moment } from 'moment';
export function initSpecHelper() {
beforeEach(() => {
// Add your matcher
jasmine.addCustomEqualityTester((a: Moment, b: Moment) => {
if (typeof a.isSame === 'function') {
return a.isSame(b);
}
});
});
}
Then, in src/test.ts import the initSpecHelper() function add execute it. I placed it before Angular's TestBed init, wich seems to work just fine.
import { initSpecHelper } from './spec_helper';
//...
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// Init our own spec helper
initSpecHelper();
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
//...

Resources