Giter Site home page Giter Site logo

voitanos / jest-preset-spfx-react16 Goto Github PK

View Code? Open in Web Editor NEW
2.0 2.0 5.0 315 KB

Jest preset configuration for SharePoint Framework projects that leverage React v16 (SPFx >=1.7.0).

License: MIT License

JavaScript 94.82% TypeScript 5.18%
enzyme jest react sharepoint-framework spfx

jest-preset-spfx-react16's People

Contributors

andrewconnell avatar baywet avatar jakestanger avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

jest-preset-spfx-react16's Issues

V1.3.1 causes different TSC rules to be applied than project settings

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.

Problem when using WebPartTitle component

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?

undefined class names

Current situation

consider the following repro

  1. scaffold a net new SPFx project (hellworld webpart, react...) on version 1.9.1
  2. execute the following command
    npm i jest @voitanos/jest-preset-spfx-react16 -D
  3. Add the following file /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();
      });
    });
  4. execute the following command 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.

Desired situation

the classes to be present so we can leverage selectors properly and implement stable unit tests.

Environment

Windows 10
node 10.16.0
jest 24.9.0

Thanks for the help!

Unable to use with ES6 modules

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';
  • SPFx 1.9.1
  • Node 10.16.3
  • Jest 23.6.0
  • @voitanos/jest-preset-spfx-react16 1.2.0

Unit testing typescript SPFx web part using jest

Question:

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

Gracefully handle failures in postinstall step

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.

Unexpected token export when running npm test

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.

  1. In the jest-preset.json file I’ve altered the “transform” configuration by adding “js” e.g. it is now
"transform": {
"^.+\\.(js|ts|tsx)$":
"ts-jest"
},
  1. In the jest-preset.json file I’ve had to add a “transformIgnorePatterns” configuration as follows:
"transformIgnorePatterns": [
"node_modules/(?!(@microsoft/sp-core-library))"
]
  1. In the tsconfig.json file I’ve had to add an “allowJs” configuration item with it’s value set to “true” and remove the “declaration” configuration value (https://www.typescriptlang....

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

jest-preset.json testMatch Question

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!

NPM postinstall error @voitanos/[email protected]

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"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.