How do I test functions using jest - javascript

If I have the following js file how would I test the getTextValue and getRadioValue functions using Jest:
function getTextValue(textArea) {
return document.getElementById(textArea).value;
}
function getRadioValue(radioGroup) {
.....
return returnedValue;
}
export default class alpha {
constructor() {
...
}
myMethod() {
const answers = {
answers: [
{ id: "1", text: getRadioValue("a")},
{ id: "2", text: getTextValue("b")}
]
};
}
}
I'd like my test to be something like:
action: myMethod is called,
expect: getTextValue toHaveReturnedWith(Element)

You should make a test file for exemple alphaTest.spec.js in your test folder:
import alpha from '/yourfolder'
describe('Alpha', () => {
test('getValue should have returned element', () => {
// act
alpha.myMethod()
// assert
expect(getTextValue).toHaveReturnedWith("b")
})
}

You don't have document context in the node environment.
You have to use the library which emulates browser functionality and populates all the necessary functions you have like document.getElementById etc.
One option is to use JSDOM and create testing HTML snippet for it.
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const textareaValue = 'My-value';
const dom = new JSDOM(`
<!DOCTYPE html>
<body>
<textarea id="textarea" value="${textareaValue}"></textarea>
</body>
`);
const { document } = dom;
function getTextValue(textArea) {
return document.getElementById(textArea).value;
}
export default class Alpha {
myMethod() {
return { id: 1, text: getTextValue("textarea")};
}
}
describe('Alpha', () => {
it('should parse textare value', () => {
const alpha = new Alpha();
expect(alpha.myMethod()).toEqual({
id: 1,
text: textareaValue
});
});
});
If you want to test complex logic and interaction with different Browser APIs better to use
Cypress, Selenium, etc. These things run actual browsers while testing but are not really recommended for just unit tests. So, option one, to use JSDOM is recommended for your case.

Related

Passing a variable between plugins in Rollup

How can I pass a variable between plugins in Rollup?
What I've tried:
// plugin-a.js
const pluginA = () => {
return {
name: 'pluginA',
async options(options) {
options.define = options.define || {};
options.define['foo'] = 'bar';
}
}
}
// plugin-b.js
const pluginB = (options = {}) => {
return {
name: 'pluginB',
buildStart: async (options) => {
console.log(options)
}
}
}
I'm getting a warning:
(!) You have passed an unrecognized option
Unknown input options: define. Allowed options: acorn, acornInjectPlugins, cache, context, experimentalCacheExpiry, external, inlineDynamicImports, input, makeAbsoluteExternalsRelative, manualChunks, maxParallelFileOps, maxParallelFileReads, moduleContext, onwarn, perf, plugins, preserveEntrySignatures, preserveModules, preserveSymlinks, shimMissingExports, strictDeprecations, treeshake, watch
It seems passing data should be done by what Rollup refers to as Direct plugin communication. This is working for me. I feel this is very hard coupled though.
function parentPlugin() {
return {
name: 'parent',
api: {
//...methods and properties exposed for other plugins
doSomething(...args) {
// do something interesting
}
}
// ...plugin hooks
};
}
function dependentPlugin() {
let parentApi;
return {
name: 'dependent',
buildStart({ plugins }) {
const parentName = 'parent';
const parentPlugin = plugins.find(plugin => plugin.name === parentName);
if (!parentPlugin) {
// or handle this silently if it is optional
throw new Error(`This plugin depends on the "${parentName}" plugin.`);
}
// now you can access the API methods in subsequent hooks
parentApi = parentPlugin.api;
},
transform(code, id) {
if (thereIsAReasonToDoSomething(id)) {
parentApi.doSomething(id);
}
}
};
}
There's also Custom module meta-data, however when I read the meta I always get null.

Writing unit test for component that uses a service

I am currently working on unit test of a VueJS project, and I would like to create a my-component.spec.js test (with Jest) for a my-component.vue component that uses a myService service with the inject option. The test itself is not important. It's above all about learning how to properly mock a component that uses a service. After doing a lot of research, I tried to write my test that I think is on the right track, but I can't seem to get it to work completely. Here is the code with 3 console.log in the test file :
mock.js (file containing a simulated method of the myService service) :
export default function getAllInfos() {
return [
{"id": "myId", "name": "myName"}
];
}
my-component.spec.js :
import {mount} from "#vue/test-utils";
import MyComponent from "./my-component.vue";
import getAllInfos from "./mock";
describe("MyComponent", () => {
it("returns the correct value for getAllInfos() method", () => {
const wrapper = mount(MyComponent, {
"provide": {
myService() {
return {
"mock": {
"getAllInfos": getAllInfos()
}
};
},
},
data() {
return {
"infos": []
};
}
});
console.log("getAllInfos = ", wrapper.vm.$options.provide.myService().mock.getAllInfos);
const test = wrapper.vm.$options.provide.myService().mock.getAllInfos;
console.log("test = ", test);
wrapper.setData({"infos": test});
console.log("infos = ", wrapper.vm.$options.data().infos);
expect(wrapper.vm.$options.data().infos).toEqual([
{"id": "myId", "name": "myName"}
]);
});
});
I think I'm on the right track because when I run the npm run test:unit command, the first 2 console.log return the expected result :
getAllInfos = [{id: 'myId', name: 'myName'}]
test = [{id: 'myId', name: 'myName'}]
However, the 3rd console.log seems strange to me :
infos = []
This means the infos data is not assigned by the test constant, the content of which is correct.
Anyone have a solution for this problem ?
If you take a closer look at the docs (setData | Vue Test Utils), then you can see a small but significant difference to your code:
// your code:
/* ... */
it("returns the correct value for getAllInfos() method", () => {
/* ... */
wrapper.setData({"infos": test});
/* ... */
});
/* ... */
// code in docs:
/* ... */
test('setData demo', async () => {
/* ... */
await wrapper.setData({ foo: 'bar' })
/* ... */
})
Yes, the difference is that in the docs, the test is an async function and the setData is awaited. I think this is the source of your problem.
You could also try (but this is a bit of a workaround):
import { createLocalVue, mount } from "#vue/test-utils";
/* ... */
const localVue = createLocalVue()
/* ... */
wrapper.setData({"infos": test});
await localVue.nextTick()
/* ... */
Source for localVue here

How to use an async function as the second parameter to jest.mock?

I need to use jest.mock together with async, await and import() so that I can use a function from another file inside the mocked module. Otherwise I must copy and paste a few hundreds of slocs or over 1000 slocs, or probably it is not even possible.
An example
This does work well:
jest.mock('./myLin.jsx', () => {
return {
abc: 967,
}
});
Everywhere I use abc later it has 967 as its value, which is different than the original one.
This does not work:
jest.mock('./myLin.jsx', async () => {
return {
abc: 967,
}
});
abc seems to not be available.
Actual issue
I need async to be able to do this:
jest.mock('~/config', async () => {
const { blockTagDeserializer } = await import(
'../editor/deserialize' // or 'volto-slate/editor/deserialize'
);
// … here return an object which contains a call to
// blockTagDeserializer declared above; if I can't do this
// I cannot use blockTagDeserializer since it is outside of
// the scope of this function
}
Actual results
I get errors like:
TypeError: Cannot destructure property 'slate' of '((cov_1viq84mfum.s[13]++) , _config.settings)' as it is undefined.
where _config, I think, is the ~/config module object and slate is a property that should be available on _config.settings.
Expected results
No error, blockTagDeserializer works in the mocked module and the unit test is passed.
The unit test code
The code below is a newer not-working code based on this file on GitHub.
import React from 'react';
import renderer from 'react-test-renderer';
import WysiwygWidget from './WysiwygWidget';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-intl-redux';
const mockStore = configureStore();
global.__SERVER__ = true; // eslint-disable-line no-underscore-dangle
global.__CLIENT__ = false; // eslint-disable-line no-underscore-dangle
jest.mock('~/config', async () => {
const { blockTagDeserializer } = await import(
'../editor/deserialize' // or 'volto-slate/editor/deserialize'
);
const createEmptyParagraph = () => {
return {
type: 'p',
children: [{ text: '' }],
};
};
return {
settings: {
supportedLanguages: [],
slate: {
elements: {
default: ({ attributes, children }) => (
<p {...attributes}>{children}</p>
),
strong: ({ children }) => {
return <strong>{children}</strong>;
},
},
leafs: {},
defaultBlockType: 'p',
textblockExtensions: [],
extensions: [
(editor) => {
editor.htmlTagsToSlate = {
STRONG: blockTagDeserializer('strong'),
};
return editor;
},
],
defaultValue: () => {
return [createEmptyParagraph()];
},
},
},
};
});
window.getSelection = () => ({});
test('renders a WysiwygWidget component', () => {
const store = mockStore({
intl: {
locale: 'en',
messages: {},
},
});
const component = renderer.create(
<Provider store={store}>
<WysiwygWidget
id="qwertyu"
title="My Widget"
description="My little description."
required={true}
value={{ data: 'abc <strong>def</strong>' }}
onChange={(id, data) => {
// console.log('changed', data.data);
// setHtml(data.data);
}}
/>
</Provider>,
);
const json = component.toJSON();
expect(json).toMatchSnapshot();
});
What I've tried
The code snippets above show partially what I have tried.
I searched the web for 'jest mock async await import' and did not found something relevant.
The question
If jest.mock is not made to work with async, what else can I do to make my unit test work?
Update 1
In the last snippet of code above, the line
STRONG: blockTagDeserializer('strong'),
uses blockTagDeserializer defined here which uses deserializeChildren, createEmptyParagraph (which is imported from another module), normalizeBlockNodes (which is imported from another module) and jsx (which is imported from another module) functions, which use deserialize which uses isWhitespace which is imported from another module and typeDeserialize which uses jsx and deserializeChildren.
Without using await import(...) syntax how can I fully mock the module so that my unit test works?
If you want to dig into our code, please note that the volto-slate/ prefix in the import statements is for the src/ folder in the repo.
Thank you.
I'd advise not doing any "heavy" stuff (whatever that means) in a callback of jest.mock, – it is designed only for mocking values.
Given your specific example, I'd just put whatever the output of blockTagDeserializer('strong') right inside the config:
jest.mock('~/config', () => {
// ...
extensions: [
(editor) => {
editor.htmlTagsToSlate = {
STRONG: ({ children }) => <strong>{children}</strong>, // or whatever this function actually returns for 'strong'
};
return editor;
},
],
// ...
});
This doesn't require anything asynchronous to be done.
If you need this setup to be present in a lot of files, extracting it in a setup file seems to be the next best thing.
I found a solution. I have a ref callback that sets the htmlTagsToSlate property of the editor in the actual code of the module, conditioned by global.__JEST__ which is defined as true in Jest command line usage:
import { htmlTagsToSlate } from 'volto-slate/editor/config';
[...]
testingEditorRef={(val) => {
ref.current = val;
if (val && global.__JEST__) {
val.htmlTagsToSlate = { ...htmlTagsToSlate };
}
}}
Now the jest.mock call for ~/config is simple, there is no need to do an import in it.
I also use this function:
const handleEditorRef = (editor, ref) => {
if (typeof ref === 'function') {
ref(editor);
} else if (typeof ref === 'object') {
ref.current = editor;
}
return editor;
};

How can I evaluate Python code in the document context from JavaScript in JupyterLab?

With Jupyter Notebooks, I could have a cell
%%javascript IPython.notebook.kernel.execute('x = 42')
Then, elsewhere in the document a Python code cell with x would show it bound to 42 as expected.
I'm trying to produce something similar with JupyterLab. I understand I'm supposed to write a plugin rather than using ad-hoc JS, and that's fine, but I'm not finding an interface to the kernel similar to the global IPython from notebooks:
import { JupyerLab, JupyterLabPlugin } from '#jupyterlab/application';
const extension: JupyterLabPlugin<void> = {
// ...
requires: [],
activate: (app: JupyterLab) => {
// can I get to Python evaluation through app?
// by adding another class to `requires` above?
}
}
export default extension;
Here's a hacky attempt that "works". Could still use advice if anyone knows where there is a public promise for the kernel being ready, how to avoid the intermediate class, or any other general improvements:
import { JupyterLab, JupyterLabPlugin } from '#jupyterlab/application';
import { DocumentRegistry } from '#jupyterlab/docregistry';
import { INotebookModel, NotebookPanel } from '#jupyterlab/notebook';
import { IDisposable, DisposableDelegate } from '#phosphor/disposable';
declare global {
interface Window {
'execPython': {
'readyState': string,
'exec': (code: string) => any,
'ready': Promise<void>
} | null
}
}
class ExecWidgetExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
createNew(nb: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
if (window.execPython) {
return;
}
window.execPython = {
'readyState': 'waiting',
'exec': null,
'ready': new Promise((resolve) => {
const wait = setInterval(() => {
if (!context.session.kernel || window.execPython.readyState === 'ready') {
return;
}
clearInterval(wait);
window.execPython.readyState = 'ready';
window.execPython.exec = (code: string) =>
context.session.kernel.requestExecute({ code }, true);
resolve();
}, 50);
})
};
// Usage elsewhere: execPython.ready.then(() => execPython.exec('x = 42').done.then(console.log, console.error))
return new DisposableDelegate(() => {});
}
}
const extension: JupyterLabPlugin<void> = {
'id': 'jupyterlab_foo',
'autoStart': true,
'activate': (app: JupyterLab) => {
app.docRegistry.addWidgetExtension('Notebook', new ExecWidgetExtension())
}
};
export default extension;

Nightwatch js Using page objects as variable in all steps

I have some page object document with code:
var gmailItemClicks = {
composeClick: function () {
return this.section.leftToolbarSection.click('#compose');
}
};
module.exports = {
commands: [gmailItemClicks],
sections: {
leftToolbarSection: {
selector: '.nH.oy8Mbf.nn.aeN',
elements: {
compose: { selector: '.T-I.J-J5-Ji.T-I-KE.L3' },
}
},
};
and the test file with many steps, like this:
module.exports = {
'1st step': function (client) {
gmail.composeClick();
},
'2d step': function (client) {
gmail.composeClick();
}
}
i can use 'gmail' variable if it is in every step like this:
module.exports = {
'1st step': function (client) {
var gmail = client.page.gmail();
gmail.composeClick();
},
'2d step': function (client) {
var gmail = client.page.gmail();
gmail.composeClick();
}
}
but i want to separate this var from the test code in the steps. I tried to use
const gmail = require('./../pages/gmail');
in the test before module.exports bloсk, and i tried to use globals.js file with the same syntax, but i get the error " ✖ TypeError: gmail.composeClick is not a function".
Now i have just one big function where are all steps used variable declared once inside the func, but the log of test looks ugly, i cant to see when the one step started and where it was stopped.
What i missed?
you could create the object in the before block. Here is how it would look like in my code:
(function gmailSpec() {
let gmailPage;
function before(client) {
gmailPage = client.page.gmail();
gmailPage.navigate()
}
function after(client) {
client.end();
}
function firstStep() {
gmailPage.composeClick()
}
function secondStep() {
gmailPage.composeClick()
}
module.exports = {
before,
after,
'1st step': firstStep,
'2nd step': secondStep
}
}());
Hope that helps you :)

Categories

Resources