Jest assert 承诺用包含的对象解决

Jest assert promise resolved with object containing

说我想测试一个 returns a Promise:

的模块
function myFunc () {
    return Promise.resolve({
        anArray: [1,2,3,4,5,6]
    })
}

使用 Jest,我如何断言 promise 解析到的对象中包含的数组的长度?

describe('myFunc', () => {
  it('returns array of length 6', () => {
    expect.assertions(1)
    return expect(myFunc()).resolves // ... something here
  })
})

如果它是同步的,我会做类似的事情:

let result = myFunc()
expect(result.anArray.length).toBe(6)

这如何与 Promises 一起使用?

一种方法是传递 done 回调,将您的测试标记为异步并强制 jest 等到您调用 done():

describe('myFunc', () => {
  it('returns array of length 6', (done) => {
    expect.assertions(1)
    myFunc().then((values) => {
      expect(values).toEqual([1,2,3...]);
      done();
    });
  })
})

你也可以 return Promise,不需要 done:

describe('myFunc', () => {
  it('returns array of length 6', () => {
    expect.assertions(1)
    return myFunc().then((values) => {
      expect(values).toEqual([1,2,3...]);
    });
  })
})

您可以阅读more about this here

有两种方法,要么 return 测试中的承诺并在 then 中做出断言,要么使用 async/await

进行测试
describe('myFunc', () => {
  it('returns array of length 6', () => {
    expect.assertions(1)
    return expect(myFunc())
      .then(result =>  expect(result).toEqual([1,2,3,4,5,6]);)
  })
})

describe('myFunc',() => {
  it('returns array of length 6', async() => {
    const result = await expect(myFunc())
    expect(result).toEqual([1,2,3,4,5,6]);)
  })
})

这个话题的docs

最简单的方法是使用 .resolves,就像您开始在示例中所做的那样。

您只需将 .toMatchObject 链接到结果:

function myFunc () {
  return Promise.resolve({
      anArray: [1,2,3,4,5,6]
  })
}

describe('myFunc', () => {
  it('returns array of length 6', () => {
    expect(myFunc()).resolves.toMatchObject({ anArray: [1,2,3,4,5,6] });  // Success!
  })
})

这将断言该对象至少 anArray 属性 设置为 [1,2,3,4,5,6](它也可以有其他属性).

注意 PR 5364 makes it so resolves validates its arguments synchronously so you don't even have to return, await, or use done if you are using Jest >= v22.2.0.


更新

听起来目标是只断言数组的长度

为此,您需要获得 Promise 的结果(如先前答案中所述),然后使用 .toHaveLength 断言 anArray 的长度属性:

describe('myFunc', () => {
  it('returns array of length 6', async () => {
    const result = await myFunc();
    expect(result.anArray).toHaveLength(6);  // Success!
  })
})