Code Monkey home page Code Monkey logo

lwc-test's Introduction

Lightning Web Components Testing Repository

This repository contains the source code of Testing utilities for Lightning Web Components. Additionally, it contains examples, documentation, meeting notes, and discussion notes for developers contributing or using Lightning Web Components.

Getting Started

Read the Lightning Web Components Unit Tests guide.

Contributing

Please refer to Lightning Web Components contributing guide here.

License

The MIT license governs your use of Lightning Web Components.

lwc-test's People

Contributors

abdulsattar avatar andrewhuffman avatar apapko avatar blittle avatar caridy avatar chelkoforce avatar dependabot[bot] avatar dexwiz avatar divmain avatar ekashida avatar j2huang avatar jasonsilberman avatar jmsjtu avatar jodarove avatar jye-sf avatar muenzpraeger avatar nolanlawson avatar oblackburn avatar pmdartus avatar ravijayaramappa avatar rochejul avatar rui-rayqiu avatar seckardt avatar stephentangcook avatar svc-scm avatar templarian avatar trentjohn avatar wjhsf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lwc-test's Issues

@lwc/jest-serializer: fails on null value

Hi

When we want to use "toMatchSnapshot" with LWC and Jest, we could have the following error (when some properties of the JSON have got a null value):

PrettyFormatPluginError: Cannot destructure property `nodeType` of 'undefined' or 'null'.TypeError: Cannot destructure property `nodeType` of 'undefined' or 'null'.

at Object.test (node_modules/@lwc/jest-serializer/src/index.js:12:14)
      at __EXTERNAL_MATCHER_TRAP__ (node_modules/expect/build/index.js:342:30)
      at Object.expect [as toMatchSnapshot] (node_modules/expect/build/index.js:343:15)
      at it.each (src/main/modules/search_lightning/searchResultsAuraAdapter/__tests__/modelMapper.test.js:88:13)

When we look on the code, we have:

function test({ nodeType } = {}) {
    return (
        nodeType &&
        (nodeType === 1 || // element
        nodeType === 3 || // text
            nodeType === 6) // comment
    );
}

According to ES6, the default value is applied only if the parameter is undefined. If we have a null value, it will not be applied.

Then, we should made instead:

function test(node) {
    const nodeType = node && node.nodeType || undefined;
    return (
        nodeType &&
        (nodeType === 1 || // element
        nodeType === 3 || // text
            nodeType === 6) // comment
    );
}

Should I create a PR?

Many thanks

Regards

Pull out `@salesforce` import transforms not relevant to OSS

In a test, the @salesforce scoped module imports will be automatically transpiled to provide a default value since the actual value would require a connection to an active app.

For example, import myMethod from '@salesforce/apex/FooController.fooMethod' will be automatically transpiled to define myMethod and set it's value to some reasonable default. In this case, myMethod will be a function that returns a resolved Promise.

Most (all?) of these @salesforce imports are not relevant to people not devloping on the Salesforce platform. We should pull these transforms out into a separate project and only apply them when tests are run on the platform.

W-6834501

jest-resolver not resolving lwc modules

The jest resolver invokes the LWC module-resolver. When Jest sees an import, it will compare against the modules returned by the LWC module resolver and then try to return a path to the module.

When the module resolver was refactored in salesforce/lwc#1414 to get rid of implicit, glob-based module resolution, the new module-resolver API is invoked but the rest of the code does not properly support it.

See this line:

This is in the alpha 3.0.0 branch.

The code is expecting a map but it's getting an array.

Support dynamic imports in Jest testing

Using dynamic imports in web applications is a common theme to minimize initial download time for web clients, like here with webpack:

const d3 = await import(/* webpackChunkName: "d3js" */ 'd3');

When running Jest in --coverage mode Jest throws the error Support for the experimental syntax 'dynamicImport' isn't currently enabled.

Typescript components are not transpiled with observable fields

There seems to be a difference in the way javascript components and typescript components are transpiled when running tests via Jest, causing reactive updates to fail as fields are no longer registered.

Looking into the Jest cache we see that the transformed TS generated by @lwc/jest-transform does not contain a constructor initializing the fields and their registerDecorators differ in that the fields property is missing.

//Transformed JS component
  constructor(...args) {
    super(...args);
    this._label = void 0;
    this._value = void 0;
    this._width = void 0;
    this._prefix = void 0;
    this._postfix = void 0;
  }

....

(0, _lwc.registerDecorators)(CurrencyInput, {
  publicProps: {
    label: {
      config: 3
    },
    value: {
      config: 3
    },
    width: {
      config: 3
    },
    prefix: {
      config: 3
    },
    postfix: {
      config: 3
    }
  },
  fields: ["_label", "_value", "_width", "_prefix", "_postfix"]
});
//Transformed TS component
(0, _lwc.registerDecorators)(CurrencyInput, {
  publicProps: {
    label: {
      config: 3
    },
    value: {
      config: 3
    },
    width: {
      config: 3
    },
    prefix: {
      config: 3
    },
    postfix: {
      config: 3
    }
  }
});

I've forked the LWC-test repo and reworked the Typescript component/test so it reproduces the issue and made a similiar javascript component for comparison here: https://github.com/JSGTrifork/lwc-test/tree/bug/typescript-test

The end result is that tests must be synchronous, that is that all property assignment must happen before the component is mounted. This limits the types of scenarios we can test in our unit testing.

Axe a11y validation error: `(duplicate-id-aria) IDs used in ARIA and labels must be unique`

Our snapshots serialize every ID and aria-* idref as [shadow-guid]:

const GUID_ATTR_VALUE = '[shadow:guid]';

This leads to HTML that Axe complains about because of apparent duplicate IDs:

<input type="text" aria-labelledby="[shadow:guid]">
<label id="[shadow:guid]">label1</label>
<input type="text" aria-labelledby="[shadow:guid]">
<label id="[shadow:guid]">label2</label>

We should:

  1. At the very least, disable this serialization in native shadow
  2. Consider another solution so that Axe doesn't complain

Add reliable downstream dependents to nucleus

We added a basic nucleus config in #230, and chose which dependents we should test based on the results of a single run in #229. That's probably not an adequate sample size to identify which dependents can be reliably tested or which ones may be broken because of us. We should re-visit the choice of dependents, and ideally enable as many as possible.

Support for LWC npm module resolution

The current version of LWC Test does not resolve 3rd party modules that are installed via npm.

The new module resolution for LWC has landed in v1.4.0, based on this RFC. To support testing with imported modules the resolver package needs to implement the new mechanism.

Issue with Jest 27.0.x

The latest Jest chokes with @lwc/jest-preset

stack trace:

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
    at Hash.update (internal/crypto/hash.js:84:11)
    at Object.getCacheKey (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/@lwc/jest-transformer/src/index.js:116:14)
    at ScriptTransformer._getCacheKey (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/@jest/transform/build/ScriptTransformer.js:280:41)
    at ScriptTransformer._getFileCachePath (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/@jest/transform/build/ScriptTransformer.js:351:27)
    at ScriptTransformer.transformSource (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/@jest/transform/build/ScriptTransformer.js:588:32)
    at revertHook.exts (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/@jest/transform/build/ScriptTransformer.js:864:18)
    at Module._compile (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/pirates/lib/index.js:93:29)
    at Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Object.newLoader [as .js] (/Users/gcordero/dist/gitsoma/rollup-poc/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:937:32)

Typescript sourcemap support

With #65 we added typescript support for LWC opensource.

In #65 a new transformation was added for .ts files, and they are transpiled to "js with lwc" syntax, leaving the transformation process for .ts files like: ts -> "lwc" -> js -> "jest". In the ts -> "lwc" transformation no sourcemaps is generated, this results in the following issues:

  1. The code coverage is not against the .ts file, but against the generated "lwc" code.
  2. The debuggable code is the "lwc" generated code on the first transformation, when ideally, it should be the typescript code.

WDIO: Support of TypeScript for LWC Open Source

Similar to Jest that got updated to support TypeScript we'll need to go through and add the build steps for wdio to run with TypeScript and JS files.

  • Build integration components with TypeScript
  • Allow __wdio__/*.spec.ts files
  • Ensure JS works after updates
  • Add examples/basicts ?

Object/Field Schema Imports with Namespace

We're currently building a managed package using LWC, and running into an issue with lwc-jest not including our namespace for schema imports.

Example:

When importing the custom account field below...

import AccountField from '@salesforce/schema/Project__c.Account__c';

We get AccountField.fieldApiName == 'namespace__Account__c' within the application

However, within tests, the namespace isn't being provided and so AccountField.fieldApiName == 'Account__c' which is causing all kinds of issues as you could imagine.

Is this a bug/oversight, or is our approach incorrect? Any insight would be super helpful; thanks guys!

Jest appears to cache uninstrumented output and utilize it in coverage runs

Repro Steps

Utilizing the latest release and Jest 26.x or 27.x:

  1. Execute a normal Jest unit test run, e.g. jest
  2. Execute a coverage Jest unit test run, e.g. jest --coverage

Result

Jest will report that tests have passed and that code coverage requirements were "met" / "passing", but does not include any files for code coverage analysis. This leads to an incorrect "passing" state and output such as:

File % Stmts % Branch % Funcs % Lines Uncovered Line #s
All files 0 0 0 0

Test Suites: 119 passed, 119 total
Tests: 1332 passed, 1332 total
Snapshots: 0 total
Time: 11.483 s

The results vary slightly based upon the execution environment.

Development Machine

The development machine will consistently report that all tests have passed, but will intermittently execute the code coverage run correctly, including files in the code coverage analysis.

CI / Jenkins

CI environments consistently manifest this error state and report that all tests have passed and show that the code coverage requirement is vacuously met.

Workaround

Adding the --no-cache option to the coverage command (e.g. jest coverage --no-cache) resolves the problem consistently in all environments.

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.