首先, 像 Getting Started 里面所说的那样, 启用babel的支持
Let's implement a module that fetches user data from an API and returns the user name.
In the above implementation, we expect the
request.js module to return a promise. We chain a call to
then to receive the user name. We chain a call to
then to receive the user name.
Now imagine an implementation of
request.js that goes to the network and fetches some user data:
Because we don't want to go to the network in our test, we are going to create a manual mock for our
request.js module in the
__mocks__ folder (the folder is case-sensitive,
__MOCKS__ will not work). 就像是这样: 就像是这样:
jest.mock('../request ') 告诉jest 使用我们手动的创建的模拟数据。 通过
resolves能更加简单地解析一个fulfilled 态的 Promise的返回值. 如果Promise是rejected态的话, 断言将会返回失败.
it 断言的是将会返回一个Promise对象. You can chain as many Promises as you like and call
expect at any time, as long as you return a Promise at the end.
There is a less verbose way using
resolves to unwrap the value of a fulfilled promise together with any other matcher. If the promise is rejected, the assertion will fail.
Writing tests using the
await syntax is also possible. Here is how you'd write the same examples from before: Here is how you'd write the same examples from before:
To enable async/await in your project, install
@babel/preset-env and enable the feature in your
.catch 方法处理错误。 请确保添加
expect.assertions 来验证一定数量的断言被调用。 否则一个fulfilled态的Promise 不会让测试失败︰
.rejects helper works like the
.resolves helper. 如果 Promise 被拒绝，则测试将自动失败。 如果 Promise 被拒绝，则测试将自动失败。
expect.assertions(number) is not required but recommended to verify that a certain number of assertions are called during a test. It is otherwise easy to forget to
The code for this example is available at examples/async.
If you'd like to test timers, like
setTimeout, take a look at the Timer mocks documentation.