SailsJS how to setup Mocha Test Framework? - express

I want to add tests to my SailsJS project, Mocha is pretty common so I decided to use it.
I configured and registered the grunt-mocha-test to run my tests when the "default" task trigger (tasks/register/default.js) runs, but it is not running anything!
How to properly configure and setup Mocha into SailsJS to run automatically with grunt?
Is it possible to run the tests manually?
Here is what I did:
1) install test packages
npm install mocha --save-dev
npm install grunt-mocha-test --save-dev
npm install sinon --save-dev
npm install assert --save-dev
3) added file tasks/config/mocha-test.js
module.exports = function(grunt) {
grunt.config.set('mochaTest', {
test: {
options: {
reporter: 'spec'
},
src: ['tests/**/*.spec.js']
}
}),
grunt.loadNpmTasks('grunt-mocha-test');
};
**3) registered tasks in tasks/register/default.js **
module.exports = function (grunt) {
grunt.registerTask('default', ['compileAssets', 'linkAssets', 'watch', 'mochaTest']);
};
2) created tests folder in the app root
tests/controller/session.spec.js
var SessionController = require('../../api/controllers/SessionController'),
sinon = require('sinon'),
assert = require('assert');
console.log('SessionController: ', SessionController);
describe('The SessionController', function () {
describe('When we load the signIn page', function () {
it ('should render the view', function () {
var view = sinon.spy();
SessionController.index(null, {
view: view
});
assert.ok(view.called);
});
});
});

I don't know that setting up a Grunt task to run your Mocha tests is the best solution. The Grunt tasks in the Sails "pipeline" are run every time you do sails lift; running your tests every time you lift the server could become very annoying as you add more tests to your suite, because you tend to do sails lift a lot during development!
You certainly can run the tests manually; you just need to install Mocha globally:
sudo npm install -g mocha
Then in your app's root directory, simply type mocha to run all the tests under /test. You can specify a subset of tests to run by giving the command a subdirectory, e.g. mocha test/controller.
As far as the tests themselves are concerned, it's possible to unit test a controller by requiring it the way you're doing, but it means you'll have to mock up request and response objects. A better way is to lift a Sails instance in your before function, and then make HTTP requests to your controllers. See answers to this question for a couple of examples of lifting Sails from within tests, either before every test or before each test. You can then use the Node http module to make requests to your controllers, or make life easier on yourself and use the request module.

Related

Could not find Cypress test run results

I created a new Vue project via npm init vue#latest and selected Cypress.
Currently there are no tests yet, I have a placeholder test /cypress/e2e/example.cy.ts with
describe("My First Test", () => {
it("visits the app root url", () => {
cy.visit("/");
});
});
I'm using Cypress v11.0.1 and have a script to run the cypress tests inside my Github Actions
"test:e2e:ci": "start-server-and-test preview :4173 'cypress run --e2e'",
This is my Cypress action
- name: Check if e2e tests are passing
uses: cypress-io/github-action#v4
with:
build: npm run build
start: npm run test:e2e:ci
Sometimes ( it occurs very rarely ) the Github workflow fails with
As you can see the test itself passes. I can fix the pipeline by running it again...
Does someone know why this happens and how to avoid this error?
Please let me know if you need more information ( e.g. configuration files )

How to pass Bitbucket pipeline repository variables to npm run script?

How do I pass a Bitbucket repository variable into the Cypress.io test script that I am running with npm run in a pipeline?
The pipeline and tests work, but I am unable to get a Bitbucket variable into the test file iteself. I can access the respository variable from bitbucket-pipeline.yml following the instructions provided by Bitbucket on the repository variable page, but I cannot access the variable inside of cypress/integration/example.js. I want to store credentials the test scripts use as Bitbucket repository variables.
Here's my code...
bitbucket-pipeline.yml
image: cypress/included:3.2.0
pipelines:
custom:
robot:
- step:
script:
- printenv
- npm ci
- npm run e2e
uses an image provided by Cypress
I can see my repository variables via printenv
package.json
{
...
"scripts": {
"e2e": "cypress run"
},
...
"dependencies": {
"cypress": "^9.4.1"
}
}
cypress/integration/example.js
describe('A', () => {
it('should B', () => {
cy.visit('https://google.com');
});
});
I want to use the Bitbucket repository variable inside of the it('should B' ...) method.
Thanks in advance for your help.
I found the Cypress.io documentation on environment variables:
https://docs.cypress.io/guides/guides/environment-variables
bitbucket-pipeline.yml
image: cypress/included:3.2.0
pipelines:
custom:
robot:
- step:
script:
- npm ci
- export CYPRESS_example=$example
- export CYPRESS_whatever=$whatever
- npm run e2e
Where example is the name of the Bitbucket repo variable. Might be case sensitive.
Add $ to reference the Bitbucket repository variable in the bitbucket-pipeline.yml file.
Use CYPRESS_ to identify it as a Cypress environment variable.
https://docs.cypress.io/guides/guides/environment-variables#Option-3-CYPRESS_
Then you can use it in the test spec via Cypress.env("example")
I actually had to typecast because Bitbucket was providing unexpected data types...
cy.get('[name="password"]').clear().type(Cypress.env("example").toString());
You can use the plugin to have a profiles for each deployment and when run the script you can set which env to run the script for example below would work if plugin setup properly inside the pipeline.
npx cypress run --env version="qa"
npx cypress run --env version="prod"

NUXT plugins CSS is not loading on production

I am using Nuxt with apollo for a project, Everything is working perfectly on a local server but on the live server, the CSS is broken for the plugins I used. I used these two plugins
vue-awesome-swiper
v-lazy-image
plugins: [
{ src: "~/plugins/vue-awesome-swiper", mode: "client" },
{ src: "~/plugins/v-lazy-image", mode: "client" }],
Here is a live demo chatfata.com. as you can see the slider is broken and blur effect in not removing after the image is render.
I am facing one more problem maybe its related to this as it's my first time using Graphql with NUXT.
On the live server, npm run build is not working. it gives some kind of node_modules/babel-loader/lib?? no recognizing the. .gql extension as you can see the screenshot
So I do npm run build on local server and upload the files to live server. I don't if both errors are related
I need help
Thanks
Run this command below:
npm install babel-loader #babel/core
And then run:
npm install && npm run build

Yarn tests on Heroku fail to connect to my back-end code

I am trying to execute tests via a Heroku pipeline with the following app.json:
{
"environments": {
"test": {
"addons": [
{
"plan": "mongolab:sandbox"
}
],
"scripts": {
"test": "yarn test && ((nohup yarn test:start:api &) && sleep 10 && yarn test:integration)"
}
}
}
}
Locally on my Linux machine the command works but on Heroku I can not reach the API service:
-----> Running test command `yarn test && ((nohup yarn test:start:api &) && sleep 10 && yarn test:integration)`...
yarn run v1.6.0
warning package.json: No license field
$ mocha-webpack --webpack-config ./webpack.config.js --require test/setup.js model/**/*.spec.js api/**/*.spec.js
WEBPACK Compiling...
WEBPACK Compiled successfully in 792ms
MOCHA Testing...
0 passing (1ms)
MOCHA Tests completed successfully
Done in 4.12s.
yarn run v1.6.0
warning package.json: No license field
$ babel-node ./server.js --presets es2015,stage-2
yarn run v1.6.0
warning package.json: No license field
$ mocha-webpack --webpack-config ./webpack.config.js --require test/setup.js model/**/*.integration.js api/**/*.integration.js
WEBPACK Compiling...
WEBPACK Compiled successfully in 1092ms
MOCHA Testing...
User
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
(node:570) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Successfully initialized mongoose-seed
Users collection cleared
Successfully created document [0] of User model
Error: Error: connect ECONNREFUSED 127.0.0.1:8080
...
How can I determine the URI to connect to the API-service itself (nohup yarn test:start:api &)?
The API is built with express-restify-mongoose and as it seems there is no out of the box testing like inject with hapijs (https://hapijs.com/api#-await-serverinjectoptions)
How can I make my tests run on Heroku?
Your tests are trying to connect to 127.0.0.1:8080, but your web application is almost certainly running elsewhere. Heroku provides the PORT environment variable telling your back-end code what port it should use.
Try updating your tests to connect to whatever that variable holds instead of 8080.

Serve SPA before running tests on cypress js

With Cypress I can test my dev subdomain easily. I have an angular/react application where when I make a dist (including index.html), I want to run Cypress tests against the built files.
Unfortunately, I have no idea how to serve a dist folder, (like serve package of npm) before starting Cypress tests.
I know that I can serve the index.html on another terminal tab, but this is not going to happen on CircleCi (my CI).
Is there anyway that Cypress can replace the localhost and serve static files before starting the actual tests?
I used browser-sync to launch a server that distribute my static files.
You need to install 3 packages: cypress (obviously), browser-sync to launch a server, and npm-run-all to launch a server and cypress consecutively.
npm install --save-dev cypress
npm install --save-dev browser-sync
npm install --save-dev npm-run-all
Here is an example of the npm scripts configuration that you will need to add in your package.json. Don't forget to customize the <port> (ex: 4000) and <folder> that contains the path to your SPA (ex: public).
{
"scripts": {
"cypress": "cypress run",
"server": "browser-sync start --port <port> --server <folder> --no-open",
"test": "run-p -r server cypress"
}
}
Now you have to write your first Hello world test:
describe('My App', function() {
it('is up', function() {
cy.visit('http://localhost:4000');
cy.contains('Hello world!');
});
});
That's it! We can launch our test:
npm test
I did the following:
I installed
npm i serve
and added
serve: "serve -s <build-folder>"
to my package.json. And then in your e.g. travis.yml you add
- npm run serve &
- npm test
The & at the end of your command will make it run in the backend and thus the test can run right after it. Since serve is pretty fast serving the static files there is no need for the npm test to wait either AND you do not have to worry about stopping the npm run serve afterwards since most CI environments are cleaning up background processes automatically after your tests finished.
Most of the information above can also be found here.