我对嘲弄很陌生,我理解断言,发现它们很简单。然而,嘲弄正在折磨我的大脑。我有一个打字稿的vue项目。问题是,我被困住了,不知道如何测试作为服务类公开的API调用。
我的思想与代码设计
apiClient
我已经创建了一个名为"apiClient“的axios实例,这样我就可以随时使用自定义配置。我已经把它存储在我的项目的根源上了。
服务
我已经将API的每个端点创建为服务文件夹中的“服务”,每个服务都是一个类,其中包含大量函数,用于获取所需的数据。
我的问题
,
我的密码
ExampleService.ts
import Approval from '@/interfaces/Approval';
import apiClient from '@/axiosConfig';
import { AxiosResponse } from 'axios';
export default class ExampleService {
// Approvals
public async getApprovals(id?: string) {
if (id != null || id !== undefined) {
return await apiClient
.get(`/api//approval/${id}`)
.then((response: AxiosResponse<Approval>) => {
return response.data;
});
} else {
return await apiClient
.get('/api/approval')
.then((response: AxiosResponse<Approval[]>) => {
return response.data;
});
}
}
public async postApproval(approval: Approval) {
return await apiClient
.post('/api/approval', approval);
}
public async putAppoval(id: string, approval: Approval) {
return await apiClient
.put(`/api/approval/${id}`, approval);
}
public async deleteApproval(id: string) {
return await apiClient
.delete(`/api/approval/${id}`);
}
}CustomAxiosInstance.ts
import axios, { AxiosResponse } from 'axios';
const apiClient = axios.create({
baseURL: `${process.env.VUE_APP_ROOT_API}`,
});
export default apiClient;我的期望
我会喜欢一些示例代码,我将如何嘲弄这一点,并解释为什么你选择做你选择的方法。请也批评我的代码。我只想提高。
发布于 2019-09-18 13:32:23
这个类的单元测试与Vue.js无关,下面是解决方案,文件夹结构:
├── ExampleService.ts
├── __tests__
│ └── ExampleService.spec.ts
├── axiosConfig.ts
└── interfaces
└── Approval.ts
2 directories, 4 files单元测试,ExampleService.spec.ts
import ExampleService from '../ExampleService';
import axios, { AxiosResponse } from 'axios';
jest.mock('axios', () => {
return {
create: jest.fn().mockReturnThis(),
get: jest.fn()
};
});
const exampleService = new ExampleService();
describe('ExampleService', () => {
beforeEach(() => {
(axios.create().get as jest.MockedFunction<typeof axios.get>).mockReset();
});
describe('#getApprovals', () => {
const mockedResponse: AxiosResponse = {
data: 'mocked data',
status: 200,
statusText: 'ok',
headers: {},
config: {}
};
it('should get approvals by id correctly', async () => {
(axios.create().get as jest.MockedFunction<typeof axios.get>).mockResolvedValueOnce(mockedResponse);
const actualValue = await exampleService.getApprovals('1');
expect(actualValue).toEqual(mockedResponse.data);
expect(axios.create().get).toBeCalledWith(`/api/approval/1`);
});
it('should get approvals correctly', async () => {
(axios.create().get as jest.MockedFunction<typeof axios.get>).mockResolvedValueOnce(mockedResponse);
const actualValue = await exampleService.getApprovals();
expect(actualValue).toEqual(mockedResponse.data);
expect(axios.create().get).toBeCalledWith(`/api/approval`);
});
});
});包含覆盖率报告的单元测试结果:
PASS src/stackoverflow/57992553/__tests__/ExampleService.spec.ts (7.041s)
ExampleService
#getApprovals
✓ should get approvals by id correctly (14ms)
✓ should get approvals correctly (3ms)
-------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------------|----------|----------|----------|----------|-------------------|
All files | 73.91 | 53.85 | 57.14 | 83.33 | |
ExampleService.ts | 70 | 53.85 | 57.14 | 80 | 19,23,27 |
axiosConfig.ts | 100 | 100 | 100 | 100 | |
-------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 8.532s我只测试getApprovals方法,您可以用相同的方式测试其他方法。
以上单元测试基于:
"jest": "^24.8.0",
"@types/jest": "^24.0.17",下面是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57992553
https://stackoverflow.com/questions/57992553
复制相似问题