importing chai assertion from chai-openapi-response-validator plugin - mocha.js

I am using Cypress.io framework, and I would like to implement chai plugin called chai-openapi-response-validator which contains a new assertion called satisfyApiSpec
https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator
I tried to install and add the plugin to the plugins/index.js file, but the assertion inside the cypress test is failing with an error: Invalid Chai property: satisfyApiSpec
Is there another way to add this plugin, so the cypress / chai will learn a new assertion?

You can add it at the top of the spec, or in cypress/support/index.js for all specs.
cypress/plugins is for node plugins, but browser-side plugins can be imported directly into specs or support/index.js.
const chai = require('chai');
const chaiResponseValidator = require('chai-openapi-response-validator').;
chai.use(chaiResponseValidator('path/to/openapi.yml'));
Getting around the fs.read() problem for this chai plugin
From npm: chai-openapi-response-validator
Loading your OpenAPI spec (3 different ways):
From an object:
// Load that OpenAPI object into this plugin
chai.use(chaiResponseValidator(openApiSpec));
so you can require the object before initializing the plugin
const chai = require('chai');
const chaiResponseValidator = require('chai-openapi-response-validator');
const openApiSpec = require('path/to/openapi.yml');
chai.use(chaiResponseValidator(openApiSpec));
An alternative - take a look at cy-spok to validate the API response.
The linked video shows in action with an intercept.

Related

How to get WebStorm to run ESLint ruletester efficiently

I am writing an ESLint plugin and I have been testing with eslint.RuleTester. This is okay, I know how to configure their test options argument but I always have to run the entire test file.
here is an example test file:
const {RuleTester} = require('eslint');
const rulester = new RuleTester({setup});
const rule = require ('myrule');
//this works also but i have to run the entire file (and thus all the tests)
ruleTester.run('myruletest',rule,{invalid,valid});
Normally, when I install a test runner I get a run/configuration for it and handy play⏯ and debug🐞 buttons in line with each test. As I write more tests (particularly in the same file) it would be handy to quickly click a => beside a test and run just that single test.
If I try to call ruletester.run from a mocha.it callback it will not report the test correctly (and definitely cannot debug / step into it).
e.g. this does not work well
const mocha = require('mocha');
const {RuleTester} = require('eslint');
const rulester = new RuleTester({setup});
const rule = require ('myrule');
// nice play button and custom run configruation but not honest test feeback
it('mytest', ()=>{
// it'll run this but will not report correctly -- `it` says it always passes
ruleTester.run('myruletest, rule, {invalid,valid});
});
it('mytest', async ()=>{
// async is of no help
await ruleTester.run('myruletest, rule, {invalid,valid});
});
//this still works also but then i have to run the entire file (and thus all the tests)
ruleTester.run('myruletest',rule,{invalid,valid});
So how do I tell WebStorm to either
recognize eslint.RuleTester as a testrunner
properly call and instance of RuleTester from my own testrunner?
Recognizing eslint.RuleTester as a test runner would require developing a special plugin.
See http://www.jetbrains.org/intellij/sdk/docs/ for basic documentation on plugin development. You can use existing plugins as example: Mocha runner is not fully open source, but its JavaScript part is open source (https://github.com/JetBrains/mocha-intellij); also, there is an open source plugin for Karma https://github.com/JetBrains/intellij-plugins/tree/master/js-karma

Docusaurus v2 and GraphQL Playground integration

I'd like to render GraphQL Playground as a React component in one of my pages but it fails due to missing file-loader in webpack. Is there a way to fix this in docs or do I need to create new plugin with new webpack config?
Is it good idea to integrate Playground and Docusaurus at all?
Thanks for your ideas...
A few Docusaurus sites have embedded playgrounds:
Hermes
Uniforms
In your case you will have to write a plugin to extend the webpack config with file-loader.
Not sure if you found a better way but check out: https://www.npmjs.com/package/graphql-playground-react
You can embed this react component directly in your react app - It looks like Apollo also uses the vanilla JS version of this
I just had exactly the same problem. Basically, Docusaurus with a gQL Playground Integration runs fine in local but won't compile due to errors when running yarn build as above.
In the end I found the answer is in Docusaurus, not in building a custom compiler:
I switched from using graphql-react-playground to GraphiQL: package: "graphiql": "^1.8.7"
This moved my error on to a weird one with no references anywhere on the web (rare for me): "no valid fetcher implementation available"
I fixed the above by importing createGraphiQLFetcher from '#graphiql/create-fetcher' to my component
Then the error was around not being able to find a window component, this was an easy one, I followed docusaurus docs here: https://docusaurus.io/docs/docusaurus-core#browseronly and wrapped my component on this page in like this:
import BrowserOnly from '#docusaurus/BrowserOnly';
const Explorer = () => {
const { siteConfig } = useDocusaurusContext();
return (
<BrowserOnly fallback={Loading...}>
{() => {
const GraphEx = GraphExplorer
return
}}
);
}
This now works and builds successfully

How to use NestJS modules in aws lambda functions

I have an NestJS application which consist of many modules: databaseModule, userModule, devicesModule, etc. They all packaged to one module ApplicationModule, which handle server actions.
But now I need to add some lambda function to my project and I need to exec some methods from databaseModule, but I don't know how to do it.
Pseudo code that I imagine:
export const handler: Handler = (event: any, context: Context, callback) => {
const dbModule = DataBaseModule.build();
dbModule.get(UserService).createProject('my_project');
callback(null, event);
};
I think that nestjs should have similar functionality but I can't find it on official page.
P.S. I can't use just UserService because it depends on other services and providers in DatabaseModule. That is why I want this module to be fully configured and I can use its services
I found an answer https://docs.nestjs.com/application-context
We can use our submodules in the next way:
const app = await NestFactory.create(ApplicationModule);
const tasksService = app.get(TasksService);
You can use the Lifecycle events from NestJS (https://docs.nestjs.com/fundamentals/lifecycle-events).
That way, you can implement OnModuleInit() on the Service and set the desired function to run when the Module is loaded (it can be sync or async).
There are some other events that can also be useful, like onApplicationBootstrap()

custom matchers how to load in jasmine-node?

I am using jasmine-node and want to reuse some custom matchers I have been using with karma. I cannot find how to load my custom matchers...
Using karma and jasmine 2.4 I can load them this way:
beforeEach(function () {
jasmine.addMatchers(customMatchers);
});
But using jasmine-node it is not working.
I must be missing something because jasmine itself is actually undefined..Can some please guide me in the right direction? Thank-you

Unable to get jasmine-jquery fixtures to load in Visual Studio with Chutzpah, or even in browser

I'm prototyping a MVC.NET 4.0 application and am defining our Javascript test configuration. I managed to get Jasmine working in VS2012 with the Chutzpah extensions, and I am able to run pure Javascript tests successfully.
However, I am unable to load test fixture (DOM) code and access it from my tests.
Here is the code I'm attempting to run:
test.js
/// various reference paths...
jasmine.getFixtures().fixturesPath = "./";
describe("jasmine tests:", function () {
it("Copies data correctly", function () {
loadFixtures('testfixture.html');
//setFixtures('<div id="wrapper"><div></div></div>');
var widget = $("#wrapper");
expect(widget).toExist();
});
});
The fixture is in the same folder as the test file. The setFixtures operation works, but when I attempt to load the HTML from a file, it doesn't. Initially, I tried to use the most recent version of jasmine-jquery from the repository, but then fell back to the over 1 year old download version 1.3.1 because it looked like there was a bug in the newer one. Here is the message I get with 1.3.1:
Test 'jasmine tests::Copies data correctly' failed
Error: Fixture could not be loaded: ./testfixture.html (status: error, message: undefined) in file:///C:/Users/db66162/SvnProjects/MvcPrototype/MvcPrototype.Tests/Scripts/jasmine/jasmine-jquery-1.3.1.js (line 103)
When I examine the source, it is doing an AJAX call, yet I'm not running in a browser. Instead, I'm using Chutzpah, which runs a headless browser (PhantomJS). When I run this in the browser with a test harness, it does work.
Is there someone out there who has a solution to this problem? I need to be able to run these tests automatically both in Visual Studio and TeamCity (which is why I am using Chutzpah). I am open to solutions that include using another test runner in place of Chutzpah. I am also going to evaluate the qUnit testing framework in this effort, so if you know that qUnit doesn't have this problem in my configuration, I will find that useful.
I fixed the issue by adding the following setting to chutzpah.json:
"TestHarnessLocationMode": "SettingsFileAdjacent",
where chutzpah.json is in my test app root
I eventually got my problem resolved. Thank you Ian for replying. I am able to use PhantomJS in TeamCity to run the tests through the test runner. I contacted the author of Chutzpah and he deployed an update to his product that solved my problem in Visual Studio. I can now run the Jasmine test using Chutzpah conventions to reference libraries and include fixtures while in VS, and use the PhantomJS runner in TeamCity to use the test runner (html).
My solution on TeamCity was to run a batch file that launches tests. So, the batch:
#echo off
REM -- Uses the PhantomJS headless browser packaged with Chutzpah to run
REM -- Jasmine tests. Does not use Chutzpah.
setlocal
set path=..\packages\Chutzpah.2.2.1\tools;%path%;
echo ##teamcity[message text='Starting Jasmine Tests']
phantomjs.exe phantom.run.js %1
echo ##teamcity[message text='Finished Jasmine Tests']
And the Javascript (phantom.run.js):
// This code lifted from https://gist.github.com/3497509.
// It takes the test harness HTML file URL as the parameter. It launches PhantomJS,
// and waits a specific amount of time before exit. Tests must complete before that
// timer ends.
(function () {
"use strict";
var system = require("system");
var url = system.args[1];
phantom.viewportSize = {width: 800, height: 600};
console.log("Opening " + url);
var page = new WebPage();
// This is required because PhantomJS sandboxes the website and it does not
// show up the console messages form that page by default
page.onConsoleMessage = function (msg) {
console.log(msg);
// Exit as soon as the last test finishes.
if (msg && msg.indexOf("Dixi.") !== -1) {
phantom.exit();
}
};
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(-1);
} else {
// Timeout - kill PhantomJS if still not done after 2 minutes.
window.setTimeout(function () {
phantom.exit();
}, 10 * 1000); // NB: use accurately, tune up referring to your needs
}
});
}());
I've got exactly the same problem. AFAIK it's to do with jasmine-jquery trying to load the fixtures via Ajax when the tests are run via the file:// URI scheme.
Apparently Chrome doesn't allow this (see https://stackoverflow.com/a/5469527/1904 and http://code.google.com/p/chromium/issues/detail?id=40787) and support amongst other browsers may vary.
Edit
You might have some joy by trying to set some PhantomJS command-line options such as --web-security=false. YMMV though: I haven't tried this myself yet, but thought I'd mention it in case it's helpful (or in case anyone else know more about this option and whether it will help).
Update
I did manage to get some joy loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment at the top of my Jasmine spec. But I still have trouble loading JSON fixtures.
Further Update
Loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment merely loads in your HTML fixtures to the Jasmine test runner, which may or may not be suitable for your needs. It doesn't load the fixtures into the jasmine-fixtures element, and consequently your fixtures don't get cleaned up after each test.

Resources