voitanos / jest-preset-spfx-react16 Goto Github PK
View Code? Open in Web Editor NEWJest preset configuration for SharePoint Framework projects that leverage React v16 (SPFx >=1.7.0).
License: MIT License
Jest preset configuration for SharePoint Framework projects that leverage React v16 (SPFx >=1.7.0).
License: MIT License
I have a question about the testMatch pattern:
**/__tests_ _/**/*.(spec|test).+(ts|js)?(x)
My google-fu may be failing me but I couldn't find any reference to a glob pattern using _ in them, and I am wondering if this is a Windows vs Mac issue. My intent was to have a "tests" folder not keep my tests in the src folder (for various reasons that don't really matter). If the folder should really be named tests that then (in Windows) hides the folder from Visual Studio Code and jest won't find the tests. If I name it 'tests' then this pattern won't find it. I obviously can add the pattern for tests and have done so but wondered if I was missing something obvious.
Thanks for this great solution it really got me up and running fast!
consider the following repro
npm i jest @voitanos/jest-preset-spfx-react16 -D
/src/webparts/helloWorld/compnents/HelloWorld.test.tsx
import * as React from 'react';
import 'jest';
import {shallow} from 'enzyme';
import toJson from 'enzyme-to-json';
import styles from './HelloWorld.module.scss';
import HelloWorld from './HelloWorld';
describe('stream tile should display properly', () => {
const wrapper = shallow(<HelloWorld description={'amazing'} />);
console.warn(`title class value ${styles.title}`);
test(`snashot should match`, () => {
expect(toJson(wrapper)).toMatchSnapshot();
});
});
npm test
the snapshot file will look something like that
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`stream tile should display properly snashot should match 1`] = `
<div>
<div>
<div>
<div>
<span>
Welcome to SharePoint!
</span>
<p>
Customize SharePoint experiences using Web Parts.
</p>
<p>
amazing
</p>
<a
href="https://aka.ms/spfx"
>
<span>
Learn more
</span>
</a>
</div>
</div>
</div>
</div>
`;
notice the absence of classes on elements.
this is problematic if I want the value "amazing" of the description as I can't write precise selectors and need to implement counting instead. This translates into flaky tests if you have complex components that display or not some elements based on some conditions.
the classes to be present so we can leverage selectors properly and implement stable unit tests.
Windows 10
node 10.16.0
jest 24.9.0
Thanks for the help!
As mentioned in #1 I'm getting Unexpected token export
. The mentioned workaround does not work for me, as I'm getting this when my React component module imports a component from Office UI Fabric React.
C:\Users\jake.stanger\Development\WebpartLibrary\node_modules\office-ui-fabric-react\lib\TextField.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './components/TextField/index';
We are going through the steps in the ReadMe for doing some Jest testing with out SPFx webparts. When we run the npm install jest @voitanos/jest-preset-spfx-react16 --save-dev it is erroring out with the following:
$ npm install jest @voitanos/jest-preset-spfx-react16 --save-dev
@voitanos/[email protected] postinstall C:\Users\kkittinger\Documents\DevOps Resp\SPFX Development\React\FAQ - Dynamic Accordion\node_modules@voitanos\jest-preset-spfx-react16
node scripts/postinstall.js
JEST PRESET POSTINSTALL STEP 1 of 4...
INFO: Adding Jest configuration file to: ./config/jest.config.json
INFO: jest.config.json not found; creating it
JEST PRESET POSTINSTALL STEP 2 of 4...
INFO: Updating NPM script 'test' to use Jest.
INFO" package.json script/test currently set to default SPFx project; updating to use jest
INFO: package.json scripts updated for Jest testing
.. run "npm test" or "npm test:watch" to run Jest tests
JEST PRESET POSTINSTALL STEP 3 of 4...
INFO: Ensure tsconfig.json includes '@types/jest' in the types
property
internal/modules/cjs/loader.js:1109
throw err;
^
SyntaxError: C:\Users\kkittinger\Documents\DevOps Resp\SPFX Development\React\FAQ - Dynamic Accordion\tsconfig.json: Unexpected token ] in JSON at position 632
at parse ()
at Object.Module._extensions..json (internal/modules/cjs/loader.js:1106:22)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (C:\Users\kkittinger\Documents\DevOps Resp\SPFX Development\React\FAQ - Dynamic Accordion\node_modules@voitanos\jest-preset-spfx-react16\scripts\postinstall.js:101:20)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
npm WARN notsup Unsupported engine for [email protected]: wanted: {"node":"^14.17.0 || ^16.13.0 || >=18.0.0"} (current: {"node":"14.16.1","npm":"6.14.12"})
npm WARN notsup Not compatible with your version of node/npm: [email protected]
npm WARN notsup Unsupported engine for [email protected]: wanted: {"node":"^14.17.0 || ^16.13.0 || >=18.0.0"} (current: {"node":"14.16.1","npm":"6.14.12"})
npm WARN notsup Not compatible with your version of node/npm: [email protected]
npm WARN notsup Unsupported engine for [email protected]: wanted: {"node":"^14.17.0 || ^16.13.0 || >=18.0.0"} (current: {"node":"14.16.1","npm":"6.14.12"})
npm WARN notsup Not compatible with your version of node/npm: [email protected]
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN @pnp/[email protected] requires a peer of @pnp/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself.
npm WARN @voitanos/[email protected] requires a peer of [email protected] but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of jest@>=26 <27 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules@rushstack\typings-generator\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @voitanos/[email protected] postinstall: node scripts/postinstall.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @voitanos/[email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
React: 16.13.1
NPM: 6.14.12
Node: 14.16.1
"@microsoft/rush-stack-compiler-3.9": "0.4.47"
Enivronment: SPFx v1.7.0, Node.js 8.14.0 (x64) and NPM 6.4.1.
Hi Andrew,
Thanks for putting this together, it speeds up and eases the initial project setup so you can get to writing your tests. It also helps by removing errors caused by missing out key configuration steps.
In striving to do more unit testing and TDD, I’ve worked through some of the great blog posts and examples that both Elio Struyf (https://www.eliostruyf.com/... and Velin Georgiev (https://github.com/VelinGeo... have put together, and now using your preset package this has helped speed things up and reduce the error risk by making things even more reproducable.
When I initially start writing and running tests everything is fine. However once I start to include components from the core Microsoft library, things start to fall over. In my case I was adding a reference to the ‘Environment’ and ‘EnvironmentType’ enum from the @microsoft/sp-core-library
. After adding this (or other references e.g. DisplayMode etc.) I would start to see an error when running my tests ‘Unexpected token import’ \node_modules@microsoft\sp-core-library\lib\index.js:11 export { default as _BrowserDetection } from './BrowserDetection';. This has been noted in an issue posted to the sp-dev-docs Github repository (https://github.com/SharePoi.... To reproduce the problem I simply took your example test "Sample.tsx" and added a reference to the EnvironmentType
from the @microsoft/sp-core-library
library.
Using your jest-preset and some more research I’ve finally managed to get it all working, but I’ve still needed to make the following tweaks.
"transform": {
"^.+\\.(js|ts|tsx)$":
"ts-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!(@microsoft/sp-core-library))"
]
With the changes above I can successfully run tests against components which include references to the sp-core-library and can build, test and run my components. I must admit I don't fully understand the implications of my changes so I now need to do further research. It would be interesting to know if you’ve hit this problem at all also?
Thanks again for putting this together.
Github Repo Reference: https://github.com/petecuttriss/spfx-jest-preset
Regards
Pete
I get a problem when I have a component that uses the WebPartTitle component (part of the @pnp/spfx-controls-react project).
In that case I get this error when running the test:
● Test suite failed to run
Cannot find module 'ControlStrings' from 'WebPartTitle.js'
at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:169:17)
at Object.<anonymous> (../node_modules/@pnp/spfx-controls-react/lib/controls/webPartTitle/WebPartTitle.js:14:15)
Any ideas on how to resolve this problem?
The postinstall step when installing the preset copies a file jest.config.js into the installer's project's config folder & edits the scripts
section in the package.json file. The user should have permission to these files, but need to add error handling when there's an exception with a message they should perform the manual step if it failed.
The change to the config to use the custom tsconfig.json
causes the transpiler rules to (very likely) mismatch those of the project using the preset, and do not match the rules of a scaffolded SPFx project.
The result of this is that tests will throw a multitude of errors when transpiling from TS(X) -> JS that do not occur when building the project.
How do you unit test the SPFx web part, written in typescript (react), that uses @pnp Call to communicate with SharePoint?
How to mock PNP call or how to make ignorable for the test case.
below I mentions the error related to PNP
E:\Projects\Unit Testing\SPFx-unit-testing\node_modules\@pnp\logging\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from "./logger";
^^^^^^
SyntaxError: Unexpected token export
3 | import { IPnpSpCrudProps } from './IPnpSpCrudProps';
4 | import { escape } from '@microsoft/sp-lodash-subset';
> 5 | require("@pnp/logging");
| ^
6 | require("@pnp/common");
7 | require("@pnp/odata");
8 | import { sp } from "@pnp/sp/presets/all";
I have configured the unit test and sample test execute successfully (without PNP)
SPFx-unit-testing
Let me know your thoughts
@andrewconnell
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.