-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Defining and importing types for Nightwatch Plugins
Plugins are a great way to extend the base functionality of Nightwatch by adding your own custom commands and assertions, and then distributing it through NPM.
And it's possible that the plugin you create might also find its audience with projects written in TypeScript. So, it's best to also ship the types for your plugins, no matter whether your plugin is written in JS or TS.
To do that, follow the below steps:
-
Create a
types/nightwatch.d.ts
file in the root of your plugin project, and mention the types as follows:// types/nightwatch.d.ts import 'nightwatch'; declare module 'nightwatch' { interface NightwatchCustomCommands { myCustomCommand(): Awaitable<NightwatchAPI, unknown>; // to be available as `browser.myCustomCommand()` myNamespace: { customCommand2(): Awaitable<NightwatchAPI, unknown>; // to be available as `browser.myNamespace.customCommand2()` } } interface NightwatchCustomAssertions { myCustomAssertion(): Awaitable<NightwatchAPI, unknown>; // to be available as `browser.myCustomAssertion()` } }
Replace the
unknown
type above with the type of the result your command or assertion returns on doingawait
. -
In
package.json
file, add a "types" property which directs to the location of the declaration file created above:"types": "./types/nightwatch.d.ts"
To use the types that are shipped by a Nightwatch plugin you are using in your project, there are three ways:
-
Add
"types"
property to the roottsconfig.json
file in your project, under"compilerOptions"
:"compilerOptions": { "types": ["plugin-name"] }
-
If you have created a
nightwatch.d.ts
file in your project (for adding types for custom-commands or page-objects), just import all the Nightwatch plugins you are using at the top of that file and you won't need to edittypes
property intsconfig.json
.For ex., if you are using
@nightwatch/apitesting
plugin, just add aimport '@nightwatch/apitesting';
statement at the top of yournightwatch.d.ts
file and you should be good to go. -
If you don't want to do any of the above steps, just add a
import 'nightwatch-plugin-name';
statement at the top of the test where you are using the plugin, and the types should get imported automatically for that plugin.
In that case, you can either contribute to the plugin by creating a pull request or define the types for that plugin in your own project by creating a types/nightwatch.d.ts
file as shown at the top of this doc in your project.
You just need to create the types/nightwatch.d.ts
file and don't need to add the types
property to package.json
. If the types still don't work, you can follow the additional steps as discussed in Page objects with Nightwatch v3 (TypeScript) wiki in the point 2.
just above the FAQs.