如何编写带有数据获取的单元测试,根据 vue js 中的响应更改数据?
How to write a unit test with data fetching, that alters data based on respone in vuejs?
我正在尝试为执行异步调用的函数编写单元测试,但它似乎并没有改变数据属性,也许我做错了什么。
检查下面的代码:
getSomething() {
MyService.getThis().then(
response => {
this.status = true;
}
).catch(error => {})
}
测试用例:
describe('test', () => {
beforeEach(() => {
// To ignore the created hook, but this doesnt work, any idea?
spyOn(CustomerData, 'created');
spyOn(MyService, 'getThis').and.returnValue(Promise.resolve(list));
});
wrapper = shallowMount(MyComponent, {
propsData: {
data: {}
},
});
it('should work', () => {
wrapper.vm.getSomething();
expect(wrapper.vm.status).toBeTruthy();
});
});
}
状态应该是真的,但它是假的,但是如果我在 getSomething() 函数中打印状态的值,它确实是真的。我不知道是什么问题。
更新:
在我写的测试用例中
it('should work', async () => {
await wrapper.vm.getSomething();
expect(wrapper.vm.status).toBeTruthy();
}
这似乎有效。这是解决问题的好方法吗?很想听听其他解决方案。
我也很感兴趣是否可以忽略创建的钩子,我还没有弄清楚。
getSomething()
里面运行的代码是异步的。 MyService.getThis()
return 承诺,如果您从远程服务获取一些数据,它的执行需要时间。
所以首先你需要 return 来自 getSomething()
的承诺
getSomething() {
return MyService.getThis()
.then(response => { this.status = true; })
.catch(error => {})
}
并且在测试内部您需要 return 在外部承诺,让开玩笑知道您的测试是异步的。
it('should work', () => {
return wrapper.vm.getSomething().then(() => {
expect(wrapper.vm.status).toBeTruthy();
});
});
或者如您在编辑部分中提到的那样,您可以使用 async
版本:
it('should work', async () => {
await getSomething();
expect(wrapper.vm.status).toBeTruthy();
});
我正在尝试为执行异步调用的函数编写单元测试,但它似乎并没有改变数据属性,也许我做错了什么。
检查下面的代码:
getSomething() {
MyService.getThis().then(
response => {
this.status = true;
}
).catch(error => {})
}
测试用例:
describe('test', () => {
beforeEach(() => {
// To ignore the created hook, but this doesnt work, any idea?
spyOn(CustomerData, 'created');
spyOn(MyService, 'getThis').and.returnValue(Promise.resolve(list));
});
wrapper = shallowMount(MyComponent, {
propsData: {
data: {}
},
});
it('should work', () => {
wrapper.vm.getSomething();
expect(wrapper.vm.status).toBeTruthy();
});
});
}
状态应该是真的,但它是假的,但是如果我在 getSomething() 函数中打印状态的值,它确实是真的。我不知道是什么问题。
更新:
在我写的测试用例中
it('should work', async () => {
await wrapper.vm.getSomething();
expect(wrapper.vm.status).toBeTruthy();
}
这似乎有效。这是解决问题的好方法吗?很想听听其他解决方案。
我也很感兴趣是否可以忽略创建的钩子,我还没有弄清楚。
getSomething()
里面运行的代码是异步的。 MyService.getThis()
return 承诺,如果您从远程服务获取一些数据,它的执行需要时间。
所以首先你需要 return 来自 getSomething()
getSomething() {
return MyService.getThis()
.then(response => { this.status = true; })
.catch(error => {})
}
并且在测试内部您需要 return 在外部承诺,让开玩笑知道您的测试是异步的。
it('should work', () => {
return wrapper.vm.getSomething().then(() => {
expect(wrapper.vm.status).toBeTruthy();
});
});
或者如您在编辑部分中提到的那样,您可以使用 async
版本:
it('should work', async () => {
await getSomething();
expect(wrapper.vm.status).toBeTruthy();
});