How can I import sinon into an ember-cli test? - ember.js

I'm trying to use sinon in my ember-cli app and I can't figure out how to import it. I have an import statement in the spec:
import { sinon } from 'sinon';
and then I try to use sinon in a test:
it('finds the todo model', function () {
var store = this.subject().store;
var spy = sinon.spy(store, 'find');
this.subject().model();
expect(spy).to.have.been.called;
});
however, when I run ember test from the command line I get this error:
not ok 8 PhantomJS 1.9 - TestLoader Failures my-app/tests/unit/routes/application-test: could not be loaded
---
message: >
Could not find module `sinon` imported from `my-app/tests/unit/routes/application-test`
stack: >
Error: Could not find module `sinon` imported from `my-app/tests/unit/routes/application-test`
at requireFrom (http://localhost:7357/assets/vendor.js:119)
at reify (http://localhost:7357/assets/vendor.js:106)
at http://localhost:7357/assets/vendor.js:149
at tryFinally (http://localhost:7357/assets/vendor.js:30)
at http://localhost:7357/assets/vendor.js:156
at http://localhost:7357/assets/test-loader.js:29
at http://localhost:7357/assets/test-loader.js:21
at http://localhost:7357/assets/test-loader.js:40
at http://localhost:7357/assets/test-support.js:13918
Log: >
...
The one thing I've noticed is that ember-sinon has a very light footprint in the bower_components/ directory:
$ls bower_components/sinon/
index.js
I've tried changing the import line to import { sinon } from 'sinon/index'; but that hasn't worked either.
Any help would be greatly appreciated. I'm very new to ember-cli, bower and es6 modules so links to background on those pieces would be greatly appreciated. Thanks!

OK, after RTFMing for litterally minutes, I found the answer right there in the test assets section of the ember-cli documentation.
The setup:
ember install ember-sinon
^ this will throw an error so I ran the generator by hand.
ember generate ember-sinon
Then, import sinon in the Brocfile:
var isProduction = EmberApp.env() === 'production';
if (!isProduction) {
app.import(app.bowerDirectory + '/sinon/index.js', {type: 'test'});
}
Now, you can use sinon.stub/spy/mock in your specs but you'll still get a jshint error about sinon not being defined. I fixed this by adding:
/* global sinon */
to the top of the spec. It looks like you should be able to declare this globally in the jshintrc file but I haven't figured that out yet.

Related

How to use Quasar 2 with AWS Amplify?

I have created the following boot file for Quasar in src/boot/amplify.js and added 'amplify' to quasar.conf.js:
import Amplify from 'aws-amplify';
import awsconfig from '../aws-exports';
import {
applyPolyfills,
defineCustomElements,
} from '#aws-amplify/ui-components/loader';
applyPolyfills().then(() => {
defineCustomElements(window);
});
Amplify.configure(awsconfig);
But I get many import errors from the line import Amplify from 'aws-amplify';:
Module not found: Can't resolve imported dependency "./printError"
App • ERROR • UI in ./node_modules/graphql/error/GraphQLError.mjs
And more -- I've gotten passed them with npm install --save graphql, but I then found many more errors for the import. It is easy to setup following Amplify docs using Vue 3 CLI and not Quasar.
Anyone had luck using Quasar or know what a possible solution might be?
is a webpack issue, check this:
https://github.com/graphql/graphql-js/issues/2721#issuecomment-723008284
I solved it by adding to the quasar.conf.js
build: {
...
extendWebpack (cfg, {isServer, isClient}) {
cfg.module.rules.push ({
test: /\.m?js/,
resolve: {
fullySpecified: false,
fallback: {crypto: false}
}
})
}
}
}
the "fallback : {crypto: false}"
it is used to resolve the subsequent error about the missing dependency of crypto-js based on:
https://stackoverflow.com/a/67076572/1550140

emberjs add bootstrap template javascript

I have a bootstrap template with custom css and js that I want to use with ember.js.
I am stuck with integrating the js.
I have to say that I usually don't work on the frontend side, so if this is an obvious mistake I made, excuse me.
I want to stick with the js I have from the template and don't want to include ember-bootstrap for example.
node version: v14.15.5, ember-cli: 3.25.0
npm packages to include: bootstrap#5.0.0-beta2, flickity, flickity-imagesloaded, flickity-as-nav-for, flickity-fade, jarallax
I have identified two tasks here. First, I need to integrate the existing npm packages. Then I need to add the custom scripts.
Current status
1. Packages
I added the npm packages to ember-cli-build.js over app.import()
// ember-cli-build.js file
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function (defaults) {
let app = new EmberApp(defaults, {});
app.import("node_modules/bootstrap/dist/js/bootstrap.min.js");
app.import("node_modules/jarallax/dist/jarallax.min.js", {
using: [{ transformation: 'cjs', as: 'jarallax' }]
});
app.import("node_modules/flickity/dist/flickity.pkgd.min.js");
app.import("node_modules/flickity-as-nav-for/as-nav-for.js");
app.import("node_modules/flickity-fade/flickity-fade.js");
app.import("node_modules/flickity-imagesloaded/flickity-imagesloaded.js");
return app.toTree();
};
When I go to the debug tab in my browser I see the packages are getting loaded under assets/node_modules/.. but js does not have any effect.
I tried to load the package in index.html over a script tag:
<script type="text/javascript" src="{{rootURL}}assets/node_modules/flickity/dist/flickity.pkgd.min.js"></script>
I get the error in the browser console window:
Refused to execute http://localhost:4200/assets/node_modules/flickity/dist/flickity.pkgd.min.js as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type.
2. Custom js scripts
The custom scripts have a moin theme.js script that imports everything else.
// js/theme.js
// Theme
import './aos';
import './bigpicture';
// ...
The imported Javascript scripts from theme.js also have imports like
// js/aos.js (imported from theme.js)
import AOS from 'aos';
const options = {
duration: 700,
easing: 'ease-out-quad',
once: true,
startEvent: 'load'
};
AOS.init(options);
The original theme.js also had import for Bootstrap and the other libraries.
// js/theme.js
// Vendor
import 'bootstrap';
import 'flickity';
// ...
import 'jarallax';
// Theme
import './aos';
import './bigpicture';
// ...
I had the js directory under vendor, public and app the import via the script tag did not work either. Importing from app.js has no effect.

How to test an ember.js engine route without the ember/no-restricted-resolver-tests eslint error?

My ember.js app uses an in-repo mountable engine called user-backoffice.
This engine provides a route called my-engine-route, and here is the unit test for it, located at my-app/lib/user-backoffice/test-support/unit/my-engine-route/route-test.js
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import engineResolverFor from 'ember-engines/test-support/engine-resolver-for';
const modulePrefix = 'user-backoffice';
const resolver = engineResolverFor(modulePrefix);
module('[user-backoffice] Unit | Route | my-engine-route', function(hooks) {
setupTest(hooks, {resolver});
test('it exists', function(assert) {
let route = this.owner.lookup('route:my-engine-route');
assert.ok(route);
});
});
The engineResolverFor part is taken from the ember-engine.com docs.
My problem is that this code generates an eslint error because of the ember/no-restricted-resolver-tests rule.
my-app/lib/user-backoffice/test-support/test-support/unit/my-engine-route/route-test.js
9:20 error Do not use setupTest whose last parameter is an object unless used in conjunction with `integration: true` ember/no-restricted-resolver-tests
In my opinion, the eslint rule and the ember-engine docs are in contradiction, so I'd like to know if the rule should be disabled in an engine's context, or if the ember-engine.com docs should be updated.
EDIT
#villander suggested in the emberjs Discord #ember-engines channel that this might be related with the ember version I am using on the project, which is indeed a bit old: 3.8.
Here is a repo to reproduce: https://github.com/bartocc/stackoverflow-question-58007416
#jul Do not send second parameter as in the form of object like wrap it up in { }.
setupTest(hooks, resolver); //this should fix your problem

Angular2 unit test + creating object of an interface

Little exhausted here, may be that is why my title is not so accurate.
I am writing a unit test for my DummyService:
import {Injectable} from '#angular/core';
#Injectable()
export class DummyService {
getAllDataSources():Promise<Array<DummyData>> {
return new Promise<DummyData[]>(resolve =>
setTimeout(()=>resolve([]), 1000) // 1 seconds
);
}
}
Please assume am returning a list of DummyData objects from getAllDataSources.
Now, I have a structure/interface for the dummy data in the same service file:
export interface DummyData{
Name:string;
IsActive:boolean;
}
I tried to write unit test for this service:
import {DummyService, DummyData} from './dummy.service';
import {
beforeEachProviders
} from '#angular/core/testing';
import {provide} from '#angular/core';
export function main() {
describe('dummy.service', () => {
let dsService:DummyService;
it('should fetch data', ()=> {
dummyData: DummyData = new DummyData(); // >>>> culprit...
expect(1).toEqual(1);
});
});
}
This unit test seem little funny, as I am really not calling DummyServices function to get the list of DummyData.
I am doing this because I was getting some issue, due to which I was not able to see my test. I did some research, spent a whole day and finally found that this structure DummyData is the CULPRIT. I proved this to myself when I tried creating an object of it in my unit test (in the code above) and I got the following error:
FAILED TESTS:
dummy.service
✖ should fetch data
PhantomJS 2.1.1 (Linux 0.0.0)
Chrome 50.0.2661 (Linux 0.0.0)
ReferenceError: **DummyData is not defined**
at eval (/home/aodev/WebstormProjects/Data Federation App/data-mapping-app/dist/dev/app/shared/datasource.service.spec.js:8:28)
at Object.eval (/home/aodev/WebstormProjects/Data Federation App/data-mapping-app/node_modules/#angular/core/testing/testing.js:80:25)
So, can someone tell me please, what am I doing wrong?
Why I cannot create the object of DummyData inside my unit test?
Please help!
TypeScript interfaces exist only during compile time, runtime knows nothing about interfaces.
This is how you create instance that implements interface:
interface itest
{
success:boolean;
}
let a:itest = {success: true}; //compiler checks that object matches interface itest

Mocha testing failed due to css in webpack

I'm new to Mocha and I am trying to use it to test a simple React component. The test would pass if the react component doesn't have any CSS styling but throws a syntax error if the tag within the React component contains any className:
Testing.react.js
import React from 'react';
export default class Testing extends React.Component {
render() {
return (
<section>
<form>
<input type="text" />
</form>
</section>
);
}
}
testing.jsx
import {
React,
sinon,
assert,
expect,
TestUtils
} from '../../test_helper';
import TestingSample from '../../../app/components/Testing.react.js';
describe('TestingSample component', function(){
before('render and locate element', function(){
var renderedComponent = TestUtils.renderIntoDocument(
<TestingSample />
);
var inputComponent = TestUtils.findRenderedDOMComponentWithTag(
renderedComponent, 'input'
);
this.inputElement = inputComponent.getDOMNode();
});
it('<input> should be of type "text"', function () {
assert(this.inputElement.getAttribute('type') === 'text');
});
})
The test would pass:
> mocha --opts ./test/javascripts/mocha.opts --compilers js:babel/register --recursive test/javascripts/**/*.jsx
TestSample component
✓ <input> should be of type "text"
1 passing (44ms)
after I added the className inside of the input tag an error shows up:
import React from 'react';
import testingStyle from '../../scss/components/landing/testing.scss';
export default class Testing extends React.Component {
render() {
return (
<section>
<form>
<input type="text" className="testingStyle.color" placeholder="Where would you like to dine" />
</form>
</section>
);
}
}
Test result:
SyntaxError: /Users/../../../Documents/project/app/scss/components/landing/testing.scss: Unexpected token (1:0)
> 1 | .color {
| ^
2 | color: red;
3 | }
I've searched online but no luck so far. Am I missing something? Please help me out or point me to the right direction would be greatly appreciated.
I'm currently using:
Node Express Server
React
React-router
Webpack
Babel
Mocha
Chai
Sinon
Sinon-Chai
There is a babel/register style hook to ignore style imports:
https://www.npmjs.com/package/ignore-styles
Install it:
npm install --save-dev ignore-styles
Run tests without styles:
mocha --require ignore-styles
you can use a css compilers run mocha, the compiler js as follow:
css-dnt-compiler.js
function donothing() {
return null;
}
require.extensions['.css'] = donothing;
require.extensions['.less'] = donothing;
require.extensions['.scss'] = donothing;
// ..etc
and run the mocha command like this:
mocha --compilers js:babel-core/register,css:css-dnt-compiler.js --recursive
My same answer as here, this is what I used to get working on Babel 6
package.json
"scripts": {
"test": "mocha --compilers js:babel-core/register
--require ./tools/testHelper.js 'src/**/*-spec.#(js|jsx)'",
tools/testHelper.js
// Prevent mocha from interpreting CSS #import files
function noop() {
return null;
}
require.extensions['.css'] = noop;
This enables you to have your tests inside your src folder alongside your components. You can add as many extensions as you would like with require.extensions.
Since you're using webpack, use null-loader to load null when webpack encounters a required CSS/LESS/SASS/etc file in your components. Install via npm and then update your webpack config to include the loader:
{
test: /(\.css|\.less|.\scss)$/,
loader: 'null-loader'
}
Obviously this will prevent you from loading CSS in your actual application, so you'll want to have a separate webpack config for your test bundle that uses this loader.
For those looking how to handle this in jest - you just add a handler for style files:
// package.json
{
"jest": {
"moduleNameMapper": {
"\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
// __mocks__/styleMock.js
module.exports = {};
More here.
None of these solutions worked for me, as I'm using mocha-webpack, and it doesn't accept the "--compilers" switch. I implemented the ignore-styles package, as described in the most popular answer, but it seemed inert, with no difference in my Istanbul coverage report (.less files still being tested).
The problem is the .less loader that I was using in my webpack.config.test.js file. Simply swapping less-loader for null-loader fixed my problem.
module: {
rules: [
{
test: /\.less$/,
use: ['null-loader']
}
]
}
For me, this is by far the simplest solution, and targets my testing configuration directly, rather than having to alter/add to the package.json scripts, or worse, add new .js files.
One simple way is to import 'ignore-styles'; in your test classes..
The code below works without any dependencies. Just add it to the top of the tests.
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function () {
if (arguments[0] && arguments[0].endsWith(".css"))
return;
return originalRequire.apply(this, arguments);
};
Although very old, this question is still relevant, so let me throw in another solution.
Use pirates, a package to add hooks to require() - if you use Babel, you already have it.
Example code:
// .test-init.js
const { addHook } = require('pirates');
const IGNORE_EXTENSIONS = ['.scss', '.svg', '.css'];
addHook((code, filename) => '', { exts: IGNORE_EXTENSIONS });
This way you can call mocha like so: mocha --require .test-init.js [whatever other parameters you use]
This is straightforward, elegant and unlike ignore-styles it doesn't imply you are ignoring styles only. Also, this is easily extendable if you need to apply some more trickery to your tests like mocking entire modules.