我是新手,并且无法确定如何测试嵌套在promises中的结果。具体做法是:
myMethod: function (e) {
let self = this
self.resetErrors()
Parser.parseFile(this.form.uploadFile).then(res => {
const hasErrors = self.validFile(res)
if (!hasErrors) {
self.processFile(res)
}
})
}
我想测试以确保假设hasErrors
为假,self.processFile
会触发。这是我目前(失败)的最佳努力:
describe("if the provided data is valid", () => {
it('runs processFile', () => {
const mockProcessFile = jest.fn()
mockParser = jest.fn(() => {
new Promise((resolve, reject) => {
return ValidMockData
}).then((loanData) => {
expect(mockProcessFile).toBeCalled()
})
})
CsvParser.parseFile = mockParser
wrapper.vm.validFile = jest.fn(true)
wrapper.vm.processFile = mockProcessFile
wrapper.vm.store().resolve((data) => {
expect(mockProcessFile).toBeCalled()
})
})
})
目前我收到Cannot read property 'then' of undefined
错误 - 这是有道理的,但我不确定我究竟应该如何在then()调用中破解期望。任何想法赞赏
答案 0 :(得分:1)
您需要在测试中存储您创建的Promise,这样您就可以使用await
让测试在解决后完成:
describe("if the provided data is valid", async() => {
it('runs processFile', () => {
const mockProcessFile = jest.fn()
const p = Promise.resolve(ValidMockData)
CsvParser.parseFile = jest.fn(() => p)
wrapper.vm.validFile = jest.fn(true)
wrapper.vm.processFile = mockProcessFile
wrapper.vm.store()
await p
expect(mockProcessFile).toBeCalled()
expect(mockProcessFile).toBeCalled()
})
})