假设我想测试一个返回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有什么关系?
有两种方法可以从测试中返回承诺并在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
一种方法是传递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();
});
})
})
你也可以返回一个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。
最简单的方法是使用.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使resolves
同步验证其参数,因此如果使用return
> = await
,您甚至不必使用done
,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!
})
})