[英]Testing vuex action that contains an async
[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon] [这是一个使用Vuex的Vue应用程序,它是使用vue-cli,mocha,chai,karma,sinon和vue-cli创建的]
I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from. 我正在尝试为我的vuex状态创建测试,但我不想使用模拟-这些测试的主要目标之一就是还要测试数据来自的API。
I am trying to follow the docs for chai-as-promised. 我正在尝试按照Chai-promise的文档进行操作。
This is a simplification of the vuex action I'm trying to test: 这是我要测试的vuex动作的简化:
const actions = {
login: (context, payload) => {
context.commit('setFlashMessage', "");
axios.get("https://first-api-call")
.then((response) => {
axios.post("https://second-api-call")
.then((response) => {
router.push({ name: "Home"});
context.commit('setFlashMessage', "Logged in successfully");
context.commit('setLogin', response.data);
});
},
Notice that the login action has two promises and doesn't return anything. 注意,登录操作有两个承诺 ,并且不返回任何内容。 The login action does two things: it sets some state and it changes the route.
登录操作有两件事:设置一些状态并更改路由。
The example that I've seen that using chai-as-promised expects that the promise is returned. 我所看到的使用chai-as-promised的示例期望返回诺言。 That is:
那是:
var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);
But in my case, login() doesn't return anything, and I'm not sure what I would return if it did. 但是在我的情况下,login()不会返回任何东西,而且我不确定如果返回的话我将返回什么。
This is what I have so far: 这是我到目前为止的内容:
import store from '@/src/store/store'
describe('login', () => {
it('bad input', () => {
store.login({ username: "abcd", password: ""});
// What is the test I should use?
}
}
I would return the login response message and make two tests. 我将返回登录响应消息并进行两个测试。 One to make sure that invalid credentials return a failure message and one to make sure that valid credentials login successfully
一种是确保无效凭据返回失败消息,另一种是确保有效凭据成功登录
My co-worker and I came up with the solution: 我和我的同事提出了解决方案:
The vuex action needs to return the promise, and they can be chained together: vuex操作需要返回承诺,并且可以将它们链接在一起:
login: (context, payload) => {
context.commit('setFlashMessage', "");
return axios.get("https://first-api-call")
.then((response) => {
return axios.post("https://second-api-call")
})
.then((response) => {
// etc...
router.push({ name: "Home"});
context.commit('setFlashMessage', "Logged in successfully");
context.commit('setLogin', response.data);
return {status: "success"};
});
},
Then we didn't need chai-as-promised because the test looks like this: 然后我们就不需要chai-promise,因为测试看起来像这样:
it('bad password', () => {
const result = store.dispatch("login", { username: userName, password: password + "bad" });
return result.then((response) => {
expect(response).to.deep.equal({ status: "failed"});
store.getters.getFlashMessage.should.equal("Error logging in");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.