gpt4 book ai didi

javascript - 我如何 Jest 测试带有 promise 的服务调用

转载 作者:行者123 更新时间:2023-11-28 20:35:27 27 4
gpt4 key购买 nike

我正在尝试 Jest 测试服务调用

这是我的代码:

service.js

uploadSomething = filename => {
return Api.post('/test')
.then(response => {return response.data;})
.catch(error => { return Promise.reject(error); });
};

我的组件.js

componentDidMount() {
this.service = new Service();
}

onUploadFile = event => {
const resp = this.service.uploadSomething(event.target.href);
resp.then(response => {
console.log(response.data);
});
}

和我的测试:

const event = {
target: {
href: 'test',
}
}
const wrapper = shallow(<myComponent />);
const myComponentInstance = wrapper.instance();
myComponentInstance.onUploadFile(event);

我尝试将 .then 添加到 myComponentInstance.onUploadFile(event),但它失败了,它返回

cannot read property 'then' of undefined, could anyone tell me how can I test this

最佳答案

解决方法如下:

myComponent.tsx:

import React, { Component } from 'react';
import { Service } from './service';

class MyComponent extends Component {
private service;

public componentDidMount() {
this.service = new Service();
}

public onUploadFile = event => {
const resp = this.service.uploadSomething(event.target.href);
return resp.then(response => {
console.log(response.data);
});
}

public render() {
return <div>my component</div>;
}
}

export default MyComponent;

service.ts:

const Api = {
async post(url) {
return { data: { data: 'real data' } };
}
};

export class Service {
public uploadSomething = filename => {
return Api.post('/test')
.then(response => {
return response.data;
})
.catch(error => {
return Promise.reject(error);
});
}
}

myComponent.spec.tsx:

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './myComponent';
import { Service } from './service';

jest.mock('./service.ts', () => {
const mockedService = {
uploadSomething: jest.fn()
};
return {
Service: jest.fn(() => mockedService)
};
});

const service = new Service();

describe('MyComponent', () => {
afterEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
});
it('should upload file correctly', async () => {
const event = {
target: {
href: 'test'
}
};
const mockedResponse = { data: 'mocked response' };
(service.uploadSomething as jest.MockedFunction<typeof service.uploadSomething>).mockResolvedValueOnce(
mockedResponse
);
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<MyComponent></MyComponent>);
const myComponentInstance = wrapper.instance() as any;
const actualValue = await myComponentInstance.onUploadFile(event);
expect(actualValue).toBeUndefined();
expect(logSpy).toBeCalledWith(mockedResponse.data);
});
});

具有 100% 覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/55828418/myComponent.spec.tsx
MyComponent
✓ should upload file correctly (24ms)

console.log node_modules/jest-mock/build/index.js:860
mocked response

-----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
myComponent.tsx | 100 | 100 | 100 | 100 | |
-----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.79s, estimated 7s

这是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55828418

关于javascript - 我如何 Jest 测试带有 promise 的服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55828418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com