I would like to write unit tests (JavaScript, Jest) for my class, but I don’t understand something. When writing a test, I need to import a class file into the test. But import calls the entire file. So, if I had a class call with the original data in the imported file, the class with the original data would be called first, and next with the test data.
- Does this mean my class is not well isolated for test?
- Shouldn’t I create a class instance in the same file as the class body? I haven’t found any contraindications anywhere, but maybe it’s bad from an architectural point of view?
- Is there a way to get around this, but I just haven’t found it yet?
Sample class:
class ABC {
constructor(settings) {
this.a = settings.a
this.b = settings.b
this.logText = settings.logText
this.sum(this.a, this.b, this.logText)
}
sum() {
console.log("log text:", this.logText)
return this.a + this.b
}
}
//Simplified settings. Originally it contains, for example: an
//asynchronous method for calling endpoint.
let settingsArray = [{
a: 1,
b: 1,
logText: "original"
}]
function createInstance () {
for(let setting from settingsArray) {
new ABC(setting);
}
}
createInstance(settingsArray)
Specifically about the problem to understand:
- in the test I import a class ABC
- the class is called, the createInstance method creates instances of the class with the original data (settingsArray). I can see log “log text: original”. I think, in correctly done test I shouldn’t see it, because in my test settingsArray is overwritten and logText != “original”.
- I’m just taking the test now
- in the test, I have overwritten settingsArray where for example: logText: “from test”
- only now I am seeing an instance of the class with test data
- even if the test passes, if the original settings contain e.g. external methods, errors are returned along the way (or later, if there were e.g. asynchronous methods). And I guess it shouldn’t be like that.
Can someone help me understand what should be good and what is wrong with my way of thinking? Maybe this is no problem, and I don’t understand correctly what is isolation for unit test?