UNPKG

2.48 kBJavaScriptView Raw
1/*
2 * Copyright (c) 2018, salesforce.com, inc.
3 * All rights reserved.
4 * SPDX-License-Identifier: MIT
5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
6 */
7const fs = require('fs');
8const { resolve, extname, join, dirname, basename } = require('path');
9
10/*
11 * In Jest version 24 the default resolver was renamed to camelCase. Temporarily
12 * support both file names until consumers upgrade their Jest version.
13 *
14 * Jest master branch has the default resolver passed as a param to custom
15 * resolvers like this. Once that is released we can remove this entire block.
16 * https://github.com/facebook/jest/commit/3f4661f141562aeca65cdad3802e930835dcf0d9
17 */
18let resolver;
19try {
20 resolver = require('jest-resolve/build/default_resolver').default;
21} catch (e) {
22 resolver = require('jest-resolve/build/defaultResolver').default;
23}
24
25const EMPTY_CSS_MOCK = resolve(__dirname, '..', 'resources', 'emptyStyleMock.js');
26const EMPTY_HTML_MOCK = resolve(__dirname, '..', 'resources', 'emptyHtmlMock.js');
27
28const WHITELISTED_LWC_PACKAGES = {
29 lwc: '@lwc/engine',
30 'wire-service': '@lwc/wire-service',
31 'wire-service-jest-util': 'lwc-wire-service-jest-util',
32};
33
34// This logic is somewhat the same in the compiler resolution system
35// We should try to consolidate it at some point.
36function isImplicitHTMLImport(importee, { basedir }) {
37 const ext = extname(importee);
38 const isHTML = ext === '.html';
39 const fileName = basename(importee, '.html');
40 const absPath = resolve(basedir, importee);
41 const jsFile = join(dirname(absPath), fileName + '.js');
42
43 return (
44 isHTML && // if is an HTML file
45 fs.existsSync(jsFile) && // There must be a js file with the same name in the same folder
46 !fs.existsSync(absPath) // and the html must not exist
47 );
48}
49
50function getLwcPath(path, options) {
51 // If is a special LWC package, resolve it from commonjs
52 if (WHITELISTED_LWC_PACKAGES[path]) {
53 return require.resolve(WHITELISTED_LWC_PACKAGES[path]);
54 }
55
56 // If is a CSS just resolve it to an empty file
57 if (extname(path) === '.css') {
58 return EMPTY_CSS_MOCK;
59 }
60
61 // If is an implicit imported html (auto-binded from the compiler) return an empty file
62 if (isImplicitHTMLImport(path, options)) {
63 return EMPTY_HTML_MOCK;
64 }
65
66 return path;
67}
68
69module.exports = function(path, options) {
70 return resolver(getLwcPath(path, options), options);
71};