I am trying to put together a basic implementation of an observable class in a js file
export class Observable {
constructor(emitter){
return this._emitter = emitter
}
foo(){
return'bar'
}
subscribe(next, error = {}, complete = {}){
if (typeof next === "function") {
return this._emitter({
next,
error: error,
complete: complete
})
}
else {
return this._emitter(next)
}
}
}
with a corresponding jest file
import { Observable } from "./observable";
describe("Observable", () => {
test('foo', () => {
let fakeAsyncData$ = new Observable();
expect(fakeAsyncData$.foo()).toBe('bar')
})
test('Observable subscriptions next returns value in pipe', () => {
let test_value = "testing"
let fakeAsyncData$ = new Observable(observer => {
observer.next(test_value);
});
fakeAsyncData$.subscribe({
next(val) { expect(val).toBe(test_value) }
});
});
});
For some reason the second test is failing due to subscribe not being a function. Which seems to be incorrect. Here is the entire jest output
FAIL ./observable.test.js
Observable
✓ foo (21 ms)
✕ Observable subscriptions next returns value in pipe (2 ms)
● Observable › Observable subscriptions next returns value in pipe
TypeError: fakeAsyncData$.subscribe is not a function
14 | });
15 |
> 16 | fakeAsyncData$.subscribe({
| ^
17 | next(val) { expect(val).toBe(test_value) }
18 | });
19 | });
at Object.subscribe (observable.test.js:16:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 0.592 s, estimated 1 s
Ran all test suites.
npm ERR! Test failed. See above for more details.
What have I managed to screw up here?
CodePudding user response:
Remove the return keyword from the constructor. You are returning the result of the assignment this._emitter = emitter
which is a function, as calling console.log(typeof fakeAsyncData$)
will tell you.
Objects instantiated via a constructor do not need to explicitly return that instance. Doing so with any non-primitive value will return that value instead. Primitive return values are ignored - see MDN.