gpt4 book ai didi

javascript - 在开 Jest 中模拟 "this"对象上的方法

转载 作者:行者123 更新时间:2023-11-30 13:54:56 25 4
gpt4 key购买 nike

我有以下实现:

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: Cannot read property '$get' of undefined

如何模拟 this.$axios.$get

我 Jest 看着模拟 global 但模拟 global 只是模拟 window.whatever。

我需要模拟这个对象。

这是我的测试:

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

关于javascript - 在开 Jest 中模拟 "this"对象上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57496293/

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