what api is this test written in? - node.js

code snippet:
describe('GetList', () => {
it('should respond with 200 Success', function* () {
let res = yield api
.get(apiPath)
.set({ })
.expect(200)
.endAsync();
res.body.forEach((item) => {
item.should.have.property('appName');
item.should.have.property('appDomain');
});
I need to write tests in the framework in which the above code is written.
if you can hint what framework it is, maybe I can read api docs and write one myself.
what I have to do is write a test that compares two arrays returned from api calls.
from npm settings it seems it use mocha and istanbul as testing framework.

That looks like Jasmine Behavior-Driven JavaScript.
Perhaps it's Mochajs as it has should.have. Jasmine, at least on the 2.4 documentation doesn't mention the should.have API.
Could you see what's included when this test is executed? Or the package.json file. Likely at the devDependencies.

Related

Best way to write unit test for Node Rest api while working with Postgres, chai and mocha?

I am working on node js rest api in which database is Postgres and we are not using any ORM. How I am writing is as below which is hitting database for create and update
it('it should create customer', (done) => {
const payload = {
customerId: "test",
customerName: "test",
customerAddress: "Some place, NWZ"
}
chai
.request(server)
.post('/customer')
.send(payload)
.end((err, res) => {
res.should.have.status(200);
res.body.success.should.equal(true);
done();
});
});
Now I want to know that what is best way to write unit test cases ? Like
Should I write unit test cases by mocking api response excluding database query ?
Or should I write unit test case which will hit database ?
Or in any way we can mock database ? What is best way to do it ?
There is some debate regarding whether unit tests should hit database. But in general, I would say hitting a real database in testing should be categories as integration test, not unit test.
So for your question 2: I would say: no, you should not write unit test case that hit database.
Then for your question 1: yes, you should mocking api response, the library you could choose, e.g. sinon.
---- Updated ----
There is an article regarding the topic, if you are interested, please refer to the following: Hitting Real Database? Unit Test and Integration Test for RESTful API in Nodejs Environment

Profiling TS-based Jest tests

I have a Typescript-based React project in which I am running jest tests (also in TS). I can run tests fine but am trying to profile the performance of some which take quite a long time to run. I have tried using Chrome Devtools to attach to the tests, which it does, however it fails due to it being TS and not plain Js. Is there any way I can profile my tests individually to see where the performance issue is occurring? Using VS Code.
Instead of a React project, it was just a regular TypeScript library for me, but I bet this also works for your use-case. I am leaving this here, in case it's usable, or for future me.
The ONLY solution I found that worked was manually setting up the profiler v8-profiler-next.
import v8Profiler from 'v8-profiler-next';
v8Profiler.setGenerateType(1);
const title = 'good-name';
describe('Should be able to generate with inputs', () => {
v8Profiler.startProfiling(title, true);
afterAll(() => {
const profile = v8Profiler.stopProfiling(title);
profile.export(function (error, result: any) {
// if it doesn't have the extension .cpuprofile then
// chrome's profiler tool won't like it.
// examine the profile:
// Navigate to chrome://inspect
// Click Open dedicated DevTools for Node
// Select the profiler tab
// Load your file
fs.writeFileSync(`${title}.cpuprofile`, result);
profile.delete();
});
});
test('....', async () => {
// Add test
});
});
This then gives you the CPU profile as such, which works fine with TypeScript.

Properly configuring mocha.json in visual studio for sails.js app testing

I am trying to startup a new project node.js with proper testing and tools.
I choose the framework sails.js , I use travis as a my CI tool https://travis-ci.org/lomithrani/InteractiveResume.
I use npm to launch my test with this line in my package.json
"test": "mocha test/bootstrap.test.js test/unit/**/*.test.js"
bootstrap.test.js:
var Sails = require('sails'),
sails;
before(function (done) {
// Increase the Mocha timeout so that Sails has enough time to lift.
this.timeout(5000);
Sails.lift({
// configuration for testing purposes
}, function (err, server) {
sails = server;
if (err) return done(err);
// here you can load fixtures, etc.
done(err, sails);
});
});
after(function (done) {
// here you can clear fixtures, etc.
Sails.lower(done);
});
the test I use as a sample:
var request = require('supertest');
describe('ResumeController', function () {
console.log('test');
describe('#hi()', function () {
it('should say hi', function (done) {
request(sails.hooks.http.app)
.get('/resume/hi')
.expect(200, done);
});
});
});
So If I run npm test or on travis everything works fine. But running it within visual studio doesn't work. As , as far as I understand it only runs the *.test.js and not the bootstrap.test.js first. I get a undefined error on sails at sails.hooks.http.app the official doc from github.com/Microsoft provide very little detail on the way to configure, only that I can create a mocha.json such as this one :
{
"ui": "tdd",
"timeout": 300000,
"reporter": "xunit"
}
but I fail to see which element I could use of https://mochajs.org/#usage
in order to execute bootstrap first.
If you have any workaround to suggest or any Idea you are very welcome.
Here is the full stacktrace I get within visual
Test Name: ResumeController #hi() should say hi
Test Outcome: Failed
Result StandardOutput:
1..1
not ok 1 ResumeController hi() should say hi
ReferenceError: sails is not defined
at Context.<anonymous> (C:\interactiveResume\test\unit\controllers\ResumeController.test.js:8:21)
at callFnAsync (C:\interactiveResume\node_modules\mocha\lib\runnable.js:306:8)
at Test.Runnable.run (C:\interactiveResume\node_modules\mocha\lib\runnable.js:261:7)
at Runner.runTest (C:\interactiveResume\node_modules\mocha\lib\runner.js:421:10)
at C:\interactiveResume\node_modules\mocha\lib\runner.js:528:12
at next (C:\interactiveResume\node_modules\mocha\lib\runner.js:341:14)
at C:\interactiveResume\node_modules\mocha\lib\runner.js:351:7
at next (C:\interactiveResume\node_modules\mocha\lib\runner.js:283:14)
at Immediate._onImmediate (C:\interactiveResume\node_modules\mocha\lib\runner.js:319:5)
# tests 1
# pass 0
# fail 1
You should use the -r or --require flag. Running directly from the command line will work.
However, that said, I'm pretty sure that the visual studio mocha.json options file doesn't support the require flag properly. Also, they haven't documented which flags are supported and which ones aren't. I've done some experimenting with modifying mocha.js in the Program Files Node.js Tools for Visual Studio folder and it looks like it only accepts certain flags where functions are already predefined in the mocha npm package.
Either way, even if you did modify this file and make it work, next time you upgrade your visual studio node.js tools, your changes would probably be blown away. There just isn't good support or documentation for this yet. I wish I didn't have a team of developers demanding all the tests worked certain ways in visual studio, otherwise I'd just use visual studio code.
I'm guessing they'll take pull requests on the mocha.js file though if you can get it working. I just don't have the time to look into it too much.

Mocha browser tests with Node.js command-line runner?

I have a suite of client-side Mocha tests that currently run with the browser test runner. But I also have a suite of server-side Mocha tests that run with the Node.js command-line test runner.
I know I can run the client-side tests from the command-line in a headless browser like PhantomJS (e.g. like this), but they'd still run separately from the server-side tests.
Is there any way to run the client-side tests as part of the command-line run?
E.g. always run both sets of tests, and have one combined output like "all 100 tests passed" or "2 tests failed" — across both client-side and server-side suites.
I imagine if this were possible, there'd need to be some sort of "proxy" layer to dynamically describe to the command-line runner each browser test, and notify it of each result (maybe even any console.log output too) as the tests ran in the browser.
Does there exist anything that achieves this? I've had a hard time finding anything. Thanks!
I use Zombie for this. There's surely a way to do it with Phantom too. Just write your client-side tests under the same directory as your server-side tests and they'll get picked up by Mocha and executed along with the rest.
I'm not sure whether you need some sample test code but here's some just in case:
var app = require('../server').app; // Spin up your server for testing
var Browser = require('zombie');
var should = require('should');
describe('Some test suite', function () {
it('should do what you expect', function (done) {
var browser = new Browser();
browser.visit('http://localhost:3000', function (err) {
// Let's say this is a log in page
should.not.exist(err);
browser
.fill('#username', 'TestUser')
.fill('#password', 'TestPassword')
.pressButton('#login', function (err) {
should.not.exist(err);
// etc...
return done();
});
});
});
});

Testing web API using jasmine and node.js

We've written a RESTful web API which responds to GET and PUT requests using node.js.
We're having some difficulties testing the API.
First, we used Zombie.js, but it's not well documented so we couldn't get it to make PUT requests:
var zombie = require("zombie");
describe("description", function() {
it("description", function() {
zombie.visit("http://localhost:3000/", function (err, browser, status) {
expect(browser.text).toEqual("A")
});
});
});
After that we tried using a REST-client called restler, which would OK, since we don't need any advanced browser simulation. This fails due to the fact that the request seems to be asynchronous - i.e. the test is useless since it finishes before the 'on success' callback is called:
var rest = require('restler');
describe("description", function() {
it("description", function() {
rest.get("http://www.google.com").on('complete', function(data, response) {
// Should fail
expect(data).toMatch(/apa/i);
});
});
});
We'd grateful for any tips about alternative testing frameworks or synchronous request clients.
For node, jasmine-node from Misko Hevery has asynchronous support and wraps jasmine.
https://github.com/mhevery/jasmine-node
You add a 'done' parameter to the test signature, and call that when the asynchronous call completes. You can also customize the timeout (the default is 500ms).
e.g. from the Github README
it("should respond with hello world", function(done) {
request("http://localhost:3000/hello", function(error, response, body){
done();
}, 250); // timeout after 250 ms
});
jasmine regular also has support for asynchronous testing with runs and waitsFor, or can use 'done' with Jasmine.Async.
I was curious about this so I did a little more research. Other than zombie, you have a couple of options...
You could use vows with the http library like this guy.
However, I think a better approach might be to use APIeasy, which is apparently built on vows. There is an awesome article over at nodejitsu that explains how to use it.
Another interesting idea is to use expresso if you are using express.

Resources