【发布时间】:2019-04-17 21:41:59
【问题描述】:
我正在尝试对在其mounted() 挂钩中进行 HTTP 调用的组件进行单元测试。我正在使用 CLI 使用 Typescript 和 Jest 创建的模板。我的组件看起来像这样:
export default class UsrUsers extends Vue {
private error: string = '';
private users: User[] | null = null;
private async mounted() {
const url = process.env.VUE_APP_SERVICE_URL;
try {
const res = await axios.get<User[]>(`${url}/api/users`);
this.users = res.data;
} catch (ex) {
this.error = (ex as AxiosError).message;
}
}
}
我找到了axios-mock-adapter 包,我有一个这样的测试设置:
describe('Users Container', () => {
const axiosMock = new MockAdapter(axios);
const baseUrl = process.env.VUE_APP_SERVICE_URL;
it('should display no user when user list is empty', async () => {
axiosMock.onGet(`${baseUrl}/api/users`).reply(200, []);
const wrapper = await shallowMount(UsrUsers);
expect(wrapper.text()).toMatch('no user');
});
});
但是,它不起作用(我也尝试使用jest.mock('axios')),我得到一个空字符串wrapper.text()。
我也尝试过像这样使用$nextTick:
it('should display no user', done => {
// Set up axiosMock
const wrapper = shallowMount(UsrUsers);
wrapper.vm.$nextTick(() => {
expect(wrapper.text()).toMatch('no user');
done();
});
});
但是消息Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout会超时
那么,我怎样才能正确地测试这个组件呢?我试图在互联网上找到一些东西,但没有找到任何东西。
【问题讨论】:
标签: typescript vuejs2 axios jestjs vue-test-utils