Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:

strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
node-version: [16.x, 18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
Expand All @@ -32,3 +32,6 @@ jobs:

- name: Run React component tests
run: npm run test-react

- name: Run Svelte component tests
run: npm run test-svelte
13 changes: 12 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { NightwatchAPI, Element } from 'nightwatch';
import { MountingOptions } from '@vue/test-utils';
import { Plugin } from 'vite';
import type { ComponentConstructorOptions, ComponentProps, SvelteComponent } from 'svelte'

type SvelteComponentOptions<T extends SvelteComponent> = Omit<
ComponentConstructorOptions<ComponentProps<T>>,
'hydrate' | 'target' | '$$inline'
>;

type GlobalMountOptions = NonNullable<MountingOptions<any>['global']>;

Expand All @@ -25,13 +31,18 @@ declare module 'nightwatch' {
},
callback?: (this: NightwatchAPI, result: Element) => void
): Awaitable<this, Element>;
mountSvelteComponent<T extends SvelteComponent>(
componentPath: string,
options?: SvelteComponentOptions<T>,
callback?: (this: NightwatchAPI, result: Element) => void
): Awaitable<this, Element>;
launchComponentRenderer(): this;
}
}

interface Options {
renderPage: string;
componentType?: 'vue' | 'react';
Comment thread
harshit-bs marked this conversation as resolved.
componentType?: 'vue' | 'react' | 'svelte';
}

export default function nightwatchPlugin(options?: Options): Plugin;
14 changes: 14 additions & 0 deletions nightwatch.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ module.exports = {
}
},

vue: {
src_folders: ['test/specs/vue'],
globals: {
componentType: 'vue'
}
},

svelte: {
src_folders: ['test/specs/svelte'],
globals: {
componentType: 'svelte'
}
},

default: {
disable_error_log: false,
launch_url: '',
Expand Down
18 changes: 8 additions & 10 deletions nightwatch/commands/importScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,20 @@ module.exports = class Command {
document.body.appendChild(scriptEl);
};

const element = await this.api
const result = await this.api
.execute(scriptFn, [scriptFileName, scriptType])
.pause(500)
.execute(function() {
return document.querySelectorAll('#app')[0].firstElementChild;
}, [], (result) => {
const componentInstance = this.api.createElement(result.value, {
isComponent: true,
type: componentType
});
}, []);

cb(componentInstance);
const componentInstance = this.api.createElement(result, {
isComponent: true,
type: componentType
});

return componentInstance;
});
cb(componentInstance);

return element;
return componentInstance;
}
};
189 changes: 189 additions & 0 deletions nightwatch/commands/mountSvelteComponent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
const AssertionError = require('assertion-error');

class NightwatchMountError extends AssertionError {
constructor(message) {
super(message);

this.name = 'NightwatchMountError';
}
}

module.exports = class Command {
get pluginSettings() {
return this.client.settings['@nightwatch/svelte'] || {};
}

getError(message) {
const err = new NightwatchMountError(message);

err.showTrace = false;
err.help = [
'run nightwatch with --devtools and --debug flags (Chrome only)',
'investigate the error in the browser console'
];

return err;
}

async mountComponent(componentName, opts, isRetry = false) {
await this.api.execute(function (innerHTML) {
function onReady(fn) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {setTimeout(fn)} else {document.addEventListener('DOMContentLoaded', fn)}
}
onReady(function() {
var scriptTag = Object.assign(document.createElement('script'), {
type: 'module',
innerHTML
});
document.body.appendChild(scriptTag);
});
}, [Command._buildScript(componentName, opts)], async (result) => {
if (result && (result.error instanceof Error) && !isRetry) {
return this.mountComponent(componentName, opts, true);
}

return result;
});
}

async command(componentName, opts = {}, cb = function() {}) {
const {
hooksRetryTimeout = 10000,
hooksRetryInterval = 150,
playFnTimeout = 20000,
playFnRetryInterval = 100
} = this.pluginSettings;

await this.api.launchComponentRenderer();
await this.mountComponent(componentName, opts);

await this.api
.waitUntil(async () => {
if (this.client.argv.debug) {
return true;
}

const result = await this.api.execute(function() {
return !!window['@@component_class'];
});

return !!result;
}, hooksRetryTimeout, hooksRetryInterval, this.getError(`time out reached (${hooksRetryTimeout}ms) while waiting for component to mount.`))

// run the play() function
.execute(function(innerHTML) {
var scriptTag = Object.assign(document.createElement('script'), {
type: 'module',
innerHTML
});
document.body.appendChild(scriptTag);
}, [`
const Component = window['@@component_class'];

if (Component && (typeof Component.play == 'function')) {
try {
window['@@playfn_result'] = await Component.play({
component: window['@@component_element']
}) || {};
} catch (err) {
console.error('Error while executing .play() function:', err);
window.__$$PlayFnError = err;
}
}
window.__$$PlayFnDone = true;
`]);

if (this.client.argv.debug) {
await this.api.debug();
} else if (this.client.argv.preview) {
await this.api.pause();
}

const result = await this.api.execute(function() {
return document.querySelectorAll('#app')[0].firstElementChild;
}, []);

if (!result) {
const err = this.getError('Could not mount the component.');

return err;
}

const componentInstance = this.api.createElement(result, {
isComponent: true,
type: 'svelte'
});

cb(componentInstance);

return componentInstance;
}

static _getMockContent(mocks = {}) {
const definitions = Object.keys(mocks);

let mockContent = '';
let mockFetch = false;
const mockFetchContent = `
function mockApiResponse(body) {
return new window.Response(JSON.stringify(body), {
status: 200,
headers: {
'Content-type': 'application/json'
}
});
}

const stubedFetch = sinon.stub(window, 'fetch');
`;

let mockFetchItemsContent = '';
if (definitions.length > 0) {
mockContent = 'import sinon from \'/node_modules/sinon/pkg/sinon-esm.js\';';
mockFetchItemsContent = definitions.reduce((prev, mockUrl) => {
const {body, type = 'fetch'} = mocks[mockUrl];
if (type === 'fetch') {
mockFetch = true;
}

prev += `
stubedFetch.withArgs('${mockUrl}').returns(sinon.promise(function (resolve, reject) {
resolve(mockApiResponse(${JSON.stringify(body)}));
}));
`;

return prev;
}, '');
}

if (mockFetch) {
mockContent += mockFetchContent;
mockContent += mockFetchItemsContent;
}

return mockContent;
}

static _buildScript(componentName, opts = {}) {

return `
import Component from '${componentName}'

${Command._getMockContent(opts.mocks)}

const element = new (Component || Component.default)({
target: document.getElementById('app'),
props: ${JSON.stringify(opts.props || {})},
context: ${opts.context},
anchor: ${opts.anchor || null},
intro: ${opts.intro || false}
});

window['@@component_element'] = element;
window['@@component_class'] = Component;
window['@@playfn_result'] = null;
window.__$$PlayFnError = null;
window.__$$PlayFnDone = false;
`;
}
};
Loading