Async mocha, chai test - javascript

I'm running the following test:
it("validates data", (done) => {
Data.run( function(success: boolean) {
expect(success).equal(true);
done();
});
});
When I run the tests this works correctly I get something like this:
✓ validates data (194ms)
However the program never exits until I press cmd+C is that the expected behaviour? When I run any other test with out a callback it exists after all tests are done.

Seems to be a Mocha 4 issue, the only solution they provide is to use the --exit flag. Something like:
mocha --require ts-node/register test/**/*.spec.ts --exit
Not ideal, but works for now.

Related

Jest set TZ env variable PER test

I am running into an issue where I want to run some of my tests under different time zones.
After following a few links i found that you can set the TZ env var before calling jest in your package.json or command line like so:
{
...
"test": "TZ=America/Sao_Paulo jest"
...
}
But this doesn't scale properly say if i want to test both America/Sao_Paulo & Asia/Shanghai...I'd have to do something like this...
{
...
"test": "TZ=America/Sao_Paulo jest & TZ=Asia/Shanghai jest"
...
}
I've also tried the approach with setting the timezone by manipulating process.env.TZ in beforeEach of each test BUT...it never actually picks up on the env when it goes runs my suites.
OK I went around the houses a bit but ended up creating a custom bash script called handleTests.sh and also renaming my test file to toUTCDate_test.ts instead of toUTCDate.test.ts to avoid jest picking it up and running it.
My package.json now looks like:
{
...
"test": "./handleTests.sh"
...
}
Make sure you run chmod +x ./handleTests.sh
handleTests.sh
# run jest like normal...
jest
# run toUTCDate tests, note _test in the file name...
# this is to dodge jest's auto-run and run only on our own terms.
for TZ in America/Los_Angeles America/Sao_Paulo Asia/Shanghai
do
TZ=$TZ jest --testRegex toUTCDate_test
done

Tests fail when I save (using `--watch` in test script config) but if I re-run manually they pass?

Not a big problem per se but I'm curious as to what's causing this behavior. I'm writing some very basic code to learn how to do some testing. I'm using jestjs for testing a node/express application, and am presently testing the development version of my project locally. All versions are up to date (most current available).
In the configuration for jest I have the following setup:
...
"test": "./node_modules/.bin/env-cmd -f ./config/test.env jest --watch"
},
"jest": {
"testEnvironment": "node",
"verbose": true
}
And my environment configuration (as referenced above by the env-cmd:
PORT=3000
SENDGRID_API_KEY=<API KEY>
JWT_SECRET=<JWT SECRET>
MONGODB_URL=mongodb://127.0.0.1:27017/task-manager-api-test
The --watch flag is supposed to work sort of like nodemon - whenever I save my test file it re-runs the tests. The problem seems to be that whenever I save the file some of the tests fail (it's fairly inconsistent as to which tests fail) - but if I manually re-run the tests (--watch gives me a CLI that allows me to re-run tests with a keypress) the tests pass.
I'm using the following in my test file to make sure that the DB instance has no data in it before running the tests:
// User to seed DB
const testUserUID = new mongoose.Types.ObjectId()
const testUser = {
_id: testUserUID,
name: 'firstName lastName',
email: 'automatedTest#test.com',
password: 'test1234',
tokens: [{
token: jwt.sign({ _id: testUserUID }, process.env.JWT_SECRET)
}]
}
// Setup
beforeEach(async () => {
await User.deleteMany()
await new User(testUser).save()
})
An Example of one of my tests:
test('Should signup a user', async () => {
await request(app)
.post('/users')
.send({
name: 'hardcodeFirst hardcodeLast',
email: 'hardcodeTest#test.com',
password: 'test1234'
})
.expect(201)
})
One of the more common errors I am getting is a MongoError:
MongoError: E11000 duplicate key error collection: task-manager-api-test.users index: email_1 dup key: { : "automatedtest#test.com" }
The other errors that are being thrown are related to the tests failing - so I'm getting values that the test does not expect.
I've tried googling some stuff related to testing async with jest but I haven't found anything that isn't shown in the documentation about how to use promises or async/await with jest. I've verified that my environment variables aren't pointing at my remote DB instance. I've run the tests in my normal (non-vscode) terminal. I've also verified that the tests always pass when using the --watch CLI (pressing Enter or a repeatedly) - the tests are only failing when I save the test file and it automatically re-runs due to the --watch flag.
Talking to one of my developer buddies it was suggested that I've possibly somehow created some sort of race condition. That would be a new situation for me if that's the case!
Thanks in advance for taking a look/any help offered!
EDIT: Included .env for my test environment
--watch flag works only for github repos. u should add watchAll
"test": "env-cmd -f ./config/test.env jest --watch"
rest of your code looks fine.

Cypress: run only one test

I want to toggle only running one test, so I don't have to wait for my other tests to see the result of one test.
Currently, I comment out my other tests, but this is really annoying.
Is there a way to toggle only running one test in Cypress?
to run only one file
cypress run --spec path/to/file.spec.js
or using glob patterns:
cypress run --spec 'path/to/files/*.spec.js'
Note: you need to wrap your glob patterns in single quotes to avoid shell expansion!
to run only one test in a file
You can use a .only as described in the Cypress docs
it.only('only run this one', () => {
// similarly use it.skip(...) to skip a test
})
it('not this one', () => {
})
Also, you can do the same with describe and context blocks
edit:
there's also a nice VSCode extension to make adding/removing .only's easier with keyboard shortcuts. It's called Test Utils (install with ext install chrisbreiding.test-utils). It works with js, coffee, and typescript:
There are multiple ways of achieving this.
You can add .onlyto it or describe see #bkucera answer
You can do it from the terminal as explained in the doc here
npx cypress run --record --spec "cypress/integration/my-spec.js"
npm run cypress -- --record --spec "cypress/integration/my-spec.js"
You can mute not needed test suites and particular cases by prepending x to testrunner methods call (describe, it, etc.)
So it would look like:
// this whole testsuite will be muted
xdescribe('Visit google', () => {
it('should visit google', () => { cy.visit('https://google.com/'); });
});
// this testsuite will run
describe('Visit youtube', () => {
it('should visit youtube', () => { cy.visit('https://youtube.com/'); });
// this testcase will be muted
xit('is not necessary', () => { ... });
});
You can run the test like this.
cypress run --spec **/file.js
The best way to do such kind runs are by using the .only keyword that cypress provide.
To run all the test cases in one describe function from many describe functions add the .only in the required describe.
describe("1st describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
describe.only("2nd describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
describe("3rd describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
So here only the 2nd describe will run.
Similarly if you want to run some test cases in 1 describe add the .only in front of all the test cases that you want to run.
describe("describe statement", () => {
it("Should check xx", async function(){
});
it.only("Should check yy", async function(){
});
it.only("Should check zz", async function(){
});
});
So here the it for yy and zz will run
This is similar to the fit and fdescribe in karma and jasmine that you might be familiar with.
You can skip the test in cypress with it.skip or xit
There is one way I have found to skip tests which I don't need to run (in the current test), and that is to use: this.skip();
it('test page', function () {
// skip this test for now
this.skip();
cy.visit('http://example.com/')
cy.contains('test page').click()
cy.url()
.should('include', '/test-page/')
})
1. it is important to use regular function as second argument of it, this will not be available in arrow function
2. Whole of the test will be skipped no matter where we write this.skip()
My test files have a structure like this path/something.test.jsx and commands npx cypress run --spec path/something.test.jsx gives the following exception in the terminal:
Can't run because no spec files were found.
We searched for any files matching this glob pattern:
...
Surprisingly enough the following works and run the test exactly for one file (providing you have jest installed):
jest path/something.test.jsx
A very easy solution is to prefix your tests in with numbers, as testing frameworks will typically will run tests in alpha/numeric order by default - so if I have to check one spec file - I will copy the contents into a file 0-[file-name].spec and re-run the test command. Once the test completes - you terminate the test run - as you will have the results you were looking for. This answer is targeted at projects where your testing framework is abstracted and as a developer, you do not have all available options for your testing framework. Not the best answer, but it works and is intuitive and super easy to do. I have found this to be a way to avoid adding a bunch of conditional skips() or only() calls that will not make it to production, will have to be removed and you can easily add the file pattern to .gitignore file so these local files do not get checked in.
The best-known solution for that already exists and requires adding just one simple argument in the console.
https://github.com/cypress-io/cypress/tree/develop/npm/grep
Simply run:
npx cypress run --env grep="TestName" --spec "filename"
Cypress .only() function is used only for development.
put .only for the test you want to execute and then run the spec as npx cypress run --spec path/to/your-file.spec.js
To run a specific file through Terminal:
npx cypress run --record --spec "cypress/integration/my-spec.js"
npm run cypress -- --record --spec "cypress/integration/my-spec.js"
You can use this
cypress run -- --spec 'path/to/files/*.spec.js'
or
npm run --spec 'path/to/files/*.spec.js'
It worked for me.
Many thanks
use the #focus keyword in the test scripts when execute using cypress open

How do I write unit tests for a single JS file?

I have a single js file with a function in in. I want to write unit tests for the function and deliver the tests and file to someone. It needs to be standalone.
Here is my project:
src: myFunction.js
tests: empty for now
myFunction.js:
function HelloWord() {
return 'Hello';
}
It would be great to have a test file like this:
import { func } from './myFunction.js';
describe('tests', function () {
it('returns hello', function () {
expect(func()).toEqual('Hello');
});
});
I don't know which unit test framework would be the easiest and fastest to accomplish what I need to do. The user needs to get my directory and just run the tests from the command line.
Using Mocha, a really fast set up would be:
1) Install mocha to package.json:
npm install --save-dev mocha
2)Write down the test. Let it be test.js under /tests/ , for example:
var myFunc = require('./myFunction');
var assert = require('assert');
describe('the function' , function(){
it('works' , function(){
assert.equal( myFunc() , 'hello');
});
});
3) Set up the package.json test command:
{
...
"scripts": {
"test": "node_modules/mocha/bin/mocha tests/test.js"
}
}
4) Call tests by npm test.

Running test cases selectively with Mocha

There is a total of 20 test case files. I want to test a particular set of 10 test cases. Is there any script file or any other method to run the test cases selectively with Mocha?
There are two principal ways to specify a subset of tests to run:
You can give Mocha the name of the file that contains the tests you want to run:
$ mocha path/to/file
It is possible to give paths to multiple files if needed. For instance, if you have 10 test files and want to run all the tests from only 2 of them, you could give the paths of the 2 files.
This method relies on you splitting your tests into separate files according to a logic that suits your situation.
You can use the --grep option:
$ mocha --grep pattern
The pattern is a regular expression that Mocha will use to test each test title. Each test for which the pattern matches will be run.
The two methods could be combined to run only tests that match a pattern and that are from one specific file: $ mocha --grep pattern path/to/file
Following command works for me
$ node_modules/.bin/mocha test/file1.js test/file2.js
mocha.describe("test1", () => {
mocha.it("test1_1", (done) => {
done();
})
mocha.it.only("test1_2", (done) => {
done();
})
})
OutPut :
test2
✔ test2_2 //because of it.only

Categories

Resources