반응형
농담으로 "이" 객체에 대한 메서드를 조롱하다
다음과 같은 구현이 있습니다.
export const actions = {
async submitPhoneNumber(context) {
let data = await this.$axios.
$get('https://jsonplaceholder.typicode.com/todos/1')
// do something with data
return data
}
}
테스트를 실행하면
TypeError: 정의되지 않은 속성 '$get'을 읽을 수 없습니다.
어떻게 조롱하지?this.$axios.$get
?
나는 조롱하는 것을 보았다.global
농담이지만 조롱하는 투덜투덜global
그저 조롱하는 창문일 뿐이지신경쓰지 말아요.
조롱할 필요가 있다this
물건.
이게 제 테스트입니다.
import { actions } from '@/store/channel-add'
import flushPromises from 'flush-promises'
describe('channel-add', () => {
it('submits phone number and returns phone code hash', async () => {
let data = await actions.submitPhoneNumber()
await flushPromises()
expect(data).toBeTruthy()
})
})
해결책은 다음과 같습니다.
index.ts
:
export const actions = {
// I don't know where you get $axios from this, you didn't give the completed code. so I made a fake one for the demo.
$axios: {
$get: url => ''
},
async submitPhoneNumber(context) {
let data = await this.$axios.$get('https://jsonplaceholder.typicode.com/todos/1');
// do something with data
data = this.processData(data);
return data;
},
// for demo
processData(data) {
return data;
}
};
index.spec.ts
:
import { actions } from './';
actions.$axios = {
$get: jest.fn()
};
describe('actions', () => {
it('should mock action.$axios.$get method', () => {
expect(jest.isMockFunction(actions.$axios.$get)).toBeTruthy();
});
it('should get data correctly', async () => {
(actions.$axios.$get as jest.Mock<any, any>).mockResolvedValueOnce({ userId: 1 });
const actualValue = await actions.submitPhoneNumber({});
expect(actualValue).toEqual({ userId: 1 });
expect(actions.$axios.$get).toBeCalledWith('https://jsonplaceholder.typicode.com/todos/1');
});
});
단위 테스트 결과:
PASS src/mock-module/axios/index.spec.ts
actions
✓ should mock action.$axios.$get method (4ms)
✓ should get data correctly (4ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 2.181s, estimated 3s
언급URL : https://stackoverflow.com/questions/57496293/mocking-a-method-on-this-object-in-jest
반응형
'itsource' 카테고리의 다른 글
localDate to java.util.날짜 및 그 반대도 단순 변환입니까? (0) | 2022.07.17 |
---|---|
v-for prop 값이 부트스트랩 모달로 업데이트되지 않음 (0) | 2022.07.17 |
수집되지 않은 참조 오류: 버스가 정의되지 않았습니까?(v.1992) (0) | 2022.07.17 |
메인스트림 OS에서 프로그램의 C/C++ 최대 스택 크기 (0) | 2022.07.17 |
Visual Studio에서의 C 프로그래밍 (0) | 2022.07.17 |