万一有人做想为此添加一个依赖项,我创建了RxJeSt。导入这个包扩展了 Jest 对 observables 的新.toEmit 断言的期望。
在空目录中创建一个最小包:
$ npm init --yes
$ npm install rxjs
$ npm install --save-dev jest rxjest
$ npm pkg set scripts.test=jest
然后将以下内容添加到index.test.js:
require("rxjest");
const { from } = require("rxjs");
it("works like this", () => {
const testObservable$ = from([{ a: 1 }, { a: 2 }, { a: 3 }]);
return expect(testObservable$).toEmit({ a: 2 });
});
您应该可以使用 npm run test 运行它并看到它失败:
$ npm t
> temp@0.1.0 test
> jest
FAIL ./index.test.js
✕ works like this (3 ms)
● works like this
expect(received).toEmit(expected) // deep equality
Expected value: "foo"
Emitted values: [{"a": 1}, {"a": 2}, {"a": 3}]
4 | it("works like this", () => {
5 | const testObservable$ = from([{ a: 1 }, { a: 2 }, { a: 3 }]);
> 6 | return expect(testObservable$).toEmit("foo");
| ^
7 | });
8 |
at Object.toEmit (index.test.js:6:34)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.306 s, estimated 1 s
Ran all test suites.
现在将期望值更新为实际发出的值,例如.toEmit({ a: 2 });,它应该通过就好了。