'What is the correct way to include one js file in another?
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|