The following JavaScript code works:
let Color = require('color');
class Example {
its_not_easy_being_green() {
return Color('green');
}
}
test('It is not easy being green', () => {
expect(new Example().its_not_easy_being_green()).toBeDefined();
})
and npx jest gets me a greenbar.
$ npx jest
PASS test/example.spec.js
✓ It is not easy being green (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.351 s, estimated 1 s
Ran all test suites.
However, any time I try to separate the class from the test I get various errors:
The most common is one about not being permitted to use import outside a module.
Or that Example is not a constructor.
What I am trying to do is move everything that isn't the three line test out of the JavaScript file that I've posted above.
If this were Java, I'd move that stuff into a separate .java file and then import that file in my test.
If this were C there would be a linker and #include involved.
What I've tried is to create an Example.js file:
let Color = require('color');
class Example {
its_not_easy_being_green() {
return Color('green');
}
}
and then require it in the test:
let Example = require('Example.js')
test('It is not easy being green', () => {
expect(new Example().its_not_easy_being_green()).toBeDefined();
})
But that gets me a complaint about Example not being a constructor, which, I suppose is true. It is a class, which presumably has a pretty inert default constructor of some kind.
I've also tried replacing the require with an import:
import('Example.js')
test('It is not easy being green', () => {
expect(new Example().its_not_easy_being_green()).toBeDefined();
})
But that gets complaints about not being permitted to use import outside a module.
Is it possible to separate the jest test from the code being tested in JavaScript?
Examplenot being a constructor, then you're apparently not exporting that constructor properly inexample.js. Please show us the code for that file too.#includein Javascript - it uses a module system instead where you export things you want to share. Best to learn the tools the language offers rather than trying to force it to do something the way a different language does things. Also, note there are two types of modules in nodejs,CommonJSmodules that userequire()andmodule.exportsandESMmodules that useimportandexport. Your project appears to be set up forCommonJSso that's what you would use unless you want to configure the project to be an ESM module project.