首页 > 解决方案 > SyntaxError: Cannot use import statement outside a module in JEST LWC

问题描述

I am trying to test my first lightning web component using visual studio code as my IDE. As instructed I installed Node.js, npm and jest dependency. But I am getting this error

Error Image

when trying to run the below code

driver_Registration.html

<template>
<div class="slds-m-around_medium">
    <p>Hello, {person}!</p>
</div>
</template>

driver_Registration.js

import { LightningElement, api } from 'lwc';

export default class Driver_Registration extends LightningElement {
@api person = 'World';
}

hello.test.js in tests folder

// hello.test.js
import { createElement } from 'lwc';
import Hello from 'c/driver_Registration';

describe('c-hello', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('displays greeting', () => {
        // Create element
        const element = createElement('c-hello', {
            is: Hello
        });
        document.body.appendChild(element);

        // Verify displayed greeting
        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, World!');
    }); 
});

Any input is appreciated

标签: salesforcelwc

解决方案


tsconfig.json

"compilerOptions": {
   ...
  "allowJs": true
}

笑话配置

添加

"transformIgnorePatterns": [
  "node_modules/(?!lwc)"
]

消除

"testPathIgnorePatterns": [
  "node_modules"
],

如果这还不够 => 开玩笑 --clearCache

希望这可以帮助


推荐阅读