Is it possible test this structire ? I have this structure
client/src/content/acs-signed-content-result.ts
export class AcsSignedContentResult {
testPubKey: string;
}
client/src/content/acs-signed-content.ts
import { AcsSignedContentResult } from "./content-result";
export class AcsSignedContent {
public async parse(acsSignContent: string, dsRootCert: string): Promise<AcsSignedContentResult> {
return new AcsSignedContentResult();
}
}
And my goal for test it, like separate peace, like unit test, like just execute parse method and check result, it should be object of class AcsSignedContentResult with some prop. SO for that I installed
package.json:
"ts-jest": "^27.1.4",
"ts-loader": "^9.2.6",
"typescript": "^4.6.4",
"#babel/preset-typescript": "^7.16.7",
"#types/jest": "^27.4.1",
"jest": "^28.0.3"
and
my conf
babel.config.js
module.exports = {
presets: [
['#babel/preset-env', {targets: {node: 'current'}}],
'#babel/preset-typescript',
],
};
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
reporters: ['default', ['./node_modules/jest-html-reporter', {
includeConsoleLog: true,
includeFailureMsg: true,
includeSuiteFailure: true,
includeObsoleteSnapshots: true
}]],
roots: [
"<rootDir>/tests"
],
testMatch: [
"**/?(*.)+(spec|test).+(ts|tsx|js)"
]
};
then I created test but I'm not sure how it should be looks correctly ?
client/tests/acs-signed-content.test.js
with
import AcsSignedContent from '../src/content/acs-signed-content';
test('test acs-signed-content result', () => {
console.log("start test acs-signed-content result");
const acsSignedContent = new AcsSignedContent();
expect(acsSignedContent.parse("acsSignContent", "dsRootCert")).toBeDefined();
});
and I try this
import { AcsSignedContent } from "../src/content/acs-signed-content";
import {AcsSignedContentResult} from "../src/content/acs-signed-content-result";
jest.mock("../src/content/acs-signed-content-result");
it("should mock class B", () => {
const functionNameMock = jest.fn();
AcsSignedContentResult.mockImplementation(() => {
return {
functionName: functionNameMock
};
});
});
and when run test faced with error
● Test suite failed to run
Jest encountered an unexpected token
///
import AcsSignedContent from '../src/content/acs-signed-content';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1773:14)
How to correct create test for this goal ?
Related
First time writing tests in typescript for my expo project. I've got some errors in my Typescript (the actual typing), but the functionality works. When I run my tests, ts-jest doesnt allow the tests to run since the types are incorrect (even though the functionality works). Is there some setting to allow ts-jest to run regardless of type errors?
App.test.tsx
import React from "react";
import renderer from "react-test-renderer";
import SignUp from "../screens/Auth/screens/SignUp";
describe("<App />", () => {
it("has 1 child", () => {
const tree = renderer.create(<SignUp />).toJSON();
console.log(tree);
});
});
jest.config.js
const { defaults: tsjPreset } = require("ts-jest/presets");
/** #type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "react-native",
transform: {
"^.+\\.jsx$": "babel-jest",
"^.+\\.tsx?$": [
"ts-jest",
{
tsconfig: "tsconfig.spec.json",
},
],
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
babel.config.js
/** #type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
}
I'm new to using Jest and I'm trying to test my helper function.
I'm not using any Typescript at the moment.
This is the error I get when I run npm run test:
TypeError: Cannot destructure property 'print' of '_graphql.default' as it is undefined.
helper.test.js:
import getDuplicateError from '../../helpers/auth'
test('Check if email already exists', () => {
error = "duplicate_email_key";
expect(getDuplicateError(error)).toBe(true);
})
auth.js:
import graphql from "graphql";
const { print } = graphql;
export const getDuplicateError = (errors) => {
/*...*/ // Actual implementation doesn't use print
};
jest.config.js
export default {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: "node",
transform: {
"^.+\\.(js|jsx)?$": "babel-jest",
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
transformIgnorePatterns: [
"node_modules/(?!variables/.*)"
],
coveragePathIgnorePatterns: [
"/node_modules/"
]
};
babel.config.json
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
package.json
"devDependencies": {
"#babel/preset-env": "^7.12.17",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"ts-jest": "^26.5.1",
"ts-node": "^9.1.1"
}
Even though print isn't being used for this function (it is used in other ones), the overall issue is that I can't test anything right now because of this issue, and will also need to be able to use it for other functions.
Is there a configuration that I need for destructuring to work? Am I not able to use destructuring on other libraries?
Will definitely prefer to be able to destructure like this because I use a lot of destructuring in my code.
Let me know if I need to provide anything else.
try to import like this
import * as graphql from "graphql";
const {print}=graphql;
graphql is not exported from graphql package and hence it is undefined. Again when you try to destructure print from it, It is throwing error.
I had to provide a mock for this one for it to ignore the destructure. I'm not sure if this is the best way to go about this but this is one solution to go past it. If someone knows of another way to go about it, I'd appreciate other responses!
jest.mock(
'graphql',
() => {
const mPrint = { t: jest.fn().mockReturnValue('test') };
return {
print: jest.fn(() => mPrint),
};
},
{ virtual: true },
);
I am writing test case using jest and react-testing-library
When i run my test script it throws an error as below
TypeError: Cannot read property 'cwd' of undefined
Now I have tried almost everything to solve this but did not find cause of this
I tried to change config , Even I have run using --no-cache but again it throws the
same error
here is my config file
const { defaults } = require("jest-config");
module.exports = {
testEnvironment: "node",
// setupFiles: [
// "<rootDir>/../apollo-server-env/dist/index.js"
// ],
preset: "ts-jest",
testMatch: null,
testRegex: ".*test*\\.(ts|tsx|js)$",
testPathIgnorePatterns: [
"/node_modules/",
"/dist/"
],
transform: {
"\\.(gql|graphql)$": "jest-transform-graphql",
"\\.(ts|tsx)$": "ts-jest",
// Use our custom transformer only for the *.js and *.jsx files
"\\.(js|jsx)?$": "./transform.js",
// future need to test with
// "^.+\\.(js|jsx|ts|tsx)$": "./transform.js",
// ".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform"
},
roots: [
"packages",
"packages-modules",
"servers"
],
moduleFileExtensions: [...defaults.moduleFileExtensions,
"ts",
"tsx",
"js",
"gql",
"graphql"],
moduleNameMapper: {
'^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
// This regex should match the packages that we want compiled from source
// through `ts-jest`, as opposed to loaded from their output files in
// `dist`.
// We don't want to match `apollo-server-env` and
// `apollo-engine-reporting-protobuf`, because these don't depend on
// compilation but need to be initialized from as parto of `prepare`.
'^(?!apollo-server-env|apollo-engine-reporting-protobuf)(apollo-(?:server|datasource|cache-control|tracing|engine)[^/]*|graphql-extensions)(?:/dist)?((?:/.*)|$)': '<rootDir>/../../packages/$1/src$2'
},
transformIgnorePatterns: [
"/node_modules/(?!(#vscode)/).*/"
],
clearMocks: true,
globals: {
__BACKEND_URL__: 'http://localhost:3010',
__GRAPHQL_URL__: 'http://localhost:8085/graphql',
/*"ts-jest": {
tsConfig: "<rootDir>/tsconfig.json",
//https://github.com/kulshekhar/ts-jest/issues/766,
"diagnostics": {
"warnOnly": true
},
"babelConfig": true
}*/
}
};```
Here is my test file
`import * as React from 'react';
import {render, cleanup} from 'react-testing-library';
import {EditorComponent} from '../components/editor/editor-component';
import { Provider } from 'react-fela';
import { createRenderer } from 'fela';
import 'jest';
import 'jest-dom/extend-expect';
import { MockedProvider } from 'react-apollo/test-utils';
import {FILE_CONTENT_QUERY} from '../../../files-graphql-client/src/queries/index';
const mocks = [{
request: {
query : FILE_CONTENT_QUERY,
},
result: {
data: {
'getReleaseNotes': {},
},
},
}];
describe('<EditorComponent/>', () => {
let componentObj, felaRenderer, props = {
subscriber: jest.fn(),
saveDelayFileChangesMutation: jest.fn(),
loadFileContent: function () {
return new Promise(function(resolve) {
setTimeout(function() {
resolve({data: {loadFileContent: {
'loadFileContent': {},
}}});
}, 300);
});
},
openingFiles: [{
value : 'test',
encoding: 'utf-8',
oldValue : 'oldTest',
deleted : false,
addIgnore : 'test',
editorId : 1,
markdown: false,
preview : true,
preOpen : false,
keepOpen : true,
status : 'test',
oversize : false,
changed : true,
changedEvent: {},
diff : true,
size : 25,
}] as IContent[],
allSave: false,
rootPath: '',
change: jest.fn(),
actions: [],
doneSaveAll: jest.fn(),
changeEditorSubscribes: jest.fn(),
updateEditorContent: jest.fn(),
openDiffEditor: jest.fn(),
closeConflicts: jest.fn(),
closeEditor: jest.fn(),
updateChangedContent: jest.fn(),
setFinderOptions: jest.fn(),
onOpenFile: jest.fn(),
styles: {},
subscribeToMore: jest.fn(),
};
beforeEach(() => {
felaRenderer = createRenderer();
componentObj = render(<MockedProvider mocks={mocks}><Provider renderer={felaRenderer}><EditorComponent {...props}/></Provider></MockedProvider>);
});
afterEach(cleanup);
});`
Just install the older version of babel-jest: 22.
No need to change the version of jest, latest version can be used.
Latest version of babel-jest creates the problem
npm install --save-dev babel-jest#22.4.3
I had the same issue and the reason was that babel-jest has been upgraded to the latest version without upgrading the rest jest-related modules:
"babel-jest": "^26.6.3",
"jest": "^23.6.0",
In my case upgrading jest to the latest version fixed the issue:
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
I ran into this problem because my jest.config.js had an incorrect transform. Per the babel-jest docs add:
"transform": {
"\\.[jt]sx?$": "babel-jest"
},
Probably the problem is the version of the "babel-jest" module. Try to allineate it with the "jest" module.
These are my dependencies in my package.json:
...
"babel-jest": "^23",
"jest": "22.4.3",
...
How can I mock an ES6 module import using Jest?
For example we have the following structure:
// ../store.js
function getData(data) {
return data / 3;
}
export { getData };
// ../myModule.js
import { getData } from './store';
function myModule(param) {
return getData(param) * 4;
}
export { myModule };
// ./myModule.test.js
import { myModule ] from '../myModule';
test('2 x 4 equal 8', () => {
expect(getData(6)).toBe(8);
});
To mock ES2015 modules, your jest config needs to use babel to convert the modules first.
You'll want to yarn add --dev babel-jest babel-preset-env
and then your package.json should look something like this:
"jest": {
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$",
"^.+\\.module\\.css$"
]
}
Secondly, in your .babelrc you need to specify your environment for test like so:
{
"presets": [
["env", "react"]
],
"env": {
"development": {
"presets": [["env"], "react"]
},
"production": {
"presets": [["env"], "react"]
},
"test": {
"presets": [["env"], "react"]
}
}
}
Once that's done, you can mock a module. For example, make a file called __mocks__/store.js (where the mocks folder is in the same level as your store.js file. Inside of your mocks file, you can do something like
const getData = () => return 42;
export { getData };
and in your myModule.test.js you need this line:
jest.mock('./store');
If you want, you can see a working example from one of my repositories here:
https://github.com/AnilRedshift/linkedINonymous/
If you want make automated test with jest, you have to include before the test/describe the next call
jest.mock('../myModule');
It returns void result from all functions.
Other alternative is mock mixed:
const mock: any = jest.genMockFromModule('../myModule');
mock.getData = jest.fn().mockImplementation(6);
The call to method getData returns 6.
I've written my React app with ES6. Now I would like to write my tests also with ES6. So the challenge here is to configure karma.
Together with google I came this far with karma.config.js (I've omitted parts of the config file which are the same!):
...
files: [
'../node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'../app/**/*.jsx',
'../test/**/*.jsx'],
preprocessors: {
'app/**/*.jsx': ['react-jsx', 'babel'],
'test/**/*.jsx': ['react-jsx', 'babel']
},
'babelPreprocessor': {
options: {
sourceMap: 'inline'
},
filename: function(file) {
return file.originalPath.replace(/\.jsx$/, '.es5.js');
},
sourceFileName: function(file) {
return file.originalPath;
}
},
....
What I think this setup should do: 1) compile the JSX to JS and next babel should transform ES6 to ES5. This together with the polyfill I expected it should run in phantomjs for example. But no, here is the output from karma when I run it:
PhantomJS 1.9.8 (Mac OS X) ERROR
SyntaxError: Parse error
at Projects/ES6/app/js/app.jsx:35
PhantomJS 1.9.8 (Mac OS X): Executed 0 of 0 ERROR (0.027 secs / 0 secs)
[20:36:59] Karma has exited with 1
Line 35 of app.jsx contains the actual JSX part. So, for some reason the preprocessors seems to do not so much. Any help with the preprocessors would be appreciated ?
UPDATE: I have this almost working nog. Turns out that the preprocessors I had should be swapped like this
'../app/**/*.jsx': ['babel', 'react'],
'../test/**/*.jsx': ['babel', 'react']
Now, when I run this, I get:
Uncaught ReferenceError: require is not defined
I thought I had a polyfill for that :(
I use ES6 with Browserify and JSX. For compilation I use Babel. The following configuration works for me.
karma.conf.js
...
frameworks: ['browserify', 'jasmine'],
files: [
'Component.js', // replace with your component
'__tests__/Component-test.js'
],
preprocessors: {
'Component.js': 'browserify',
'./__tests__/Component-test.js': 'browserify'
},
browserify : {
transform : ['babelify']
},
...
__tests__/Component-test.js
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var Component = require('../Component.js');
describe('Component', () => {
it('should work', () => {
var component = <Component />;
TestUtils.renderIntoDocument(component);
expect(component).toBeTruthy();
});
});
If you have any questions let me know.
#zemirico answer did not work for me and is slightly outdated.
Here is my own setup that you can use for karma.conf.js:
...
frameworks: ['jasmine', 'browserify'],
files: [
'src/*',
'tests/*'
],
preprocessors: {
'src/*': ['browserify'],
'tests/*': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify']
}
...
It uses babelify instead of reactify, and has other dependencies. Thus, .babelrc in the project root is also needed:
{
presets: ['es2015', 'react']
}
The setup also requires the dependencies below to be included in package.json file:
"devDependencies": {
"babel-preset-react": "^6.5.0",
"babelify": "^7.2.0",
"browserify": "^13.0.0",
"jasmine-core": "^2.4.1",
"karma": "^0.13.22",
"karma-browserify": "^5.0.3",
"karma-chrome-launcher": "^0.2.3",
"karma-jasmine": "^0.3.8",
"watchify": "^3.7.0",
"babel-preset-es2015": "^6.6.0",
"react": "^15.0.1",
"react-addons-test-utils": "^15.0.1",
"react-dom": "^15.0.1"
}
Usage
Create a new React component in src/my-element.jsx:
import React from 'react';
export default class MyElement extends React.Component {
constructor(props) {
super(props);
this.state = {isActive: false};
this.onClick = this.onClick.bind(this);
}
onClick() {
this.setState({isActive: !this.state.isActive});
}
render() {
return (
<div onClick={this.onClick}>{this.state.isActive ? "I am active!" : "I am not active :("}</div>
);
}
}
Then, test it as such by creating spec in tests/my-element-spec.js:
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import MyElement from '../src/my-element.jsx';
describe('MyElement', () => {
// Render a checkbox with label in the document
const element = TestUtils.renderIntoDocument(<MyElement />);
const elementNode = ReactDOM.findDOMNode(element);
it('verity correct default text', () => {
expect(elementNode.textContent).toEqual('I am not active :(');
});
it ('verify text has been changed successfuly after click', () => {
// Simulate a click and verify that it is now On
TestUtils.Simulate.click(elementNode);
// Verify text has been changed successfully
expect(elementNode.textContent).toEqual('I am active!');
});
});
Demo
Working example on GitHub.