09|mock深入学习

2020-05-24  本文已影响0人  雪燃归来

一、之前用的mock行为

//demo.js
import axios from 'axios'
export const fetData = () => {
    return axios.get('/').then(res => res.data)
}

//demo.test.js
import { fetData } from './demo'
import axios from 'axios'
jest.mock('axios')
test('fetchData 测试', () => {
    axios.get.mockResolvedValue({
        data: '(function(){return "123"})()'
    })
    return fetData().then(data => {
        expect(eval(data)).toEqual('123')
    })
})

二、编写mock文件,替代真实的=异步请求代码

//__mocks__/demo.js
export const fetData = () => {
    return new Promise((resolved, reject) => {
        resolved('(function(){return "123"})()')
    })
} 
// demo.js
import axios from 'axios'
export const fetData = () => {
    return axios.get('/').then(res => res.data)
} 
//demo.test.js
jest.mock('./demo')
import { fetData } from './demo'
test('fetchData 测试', () => {
    return fetData().then(data => {
        expect(eval(data)).toEqual('123')
    })
})

三、取消mock和自动mock

jest.unmock('./demo')
// jest.config.js
//   automock: false,

四、在mock的设置下访问真实的文件

//__mocks__/demo.js
export const fetData = () => {
    return new Promise((resolved, reject) => {
        resolved('(function(){return "123"})()')
    })
} 

// demo.js
import axios from 'axios'
export const fetData = () => {
    return axios.get('/').then(res => res.data)
} 
export const getNumber = () => {
    return 123
}

//demo.test.js
jest.mock('./demo')
import { fetData } from './demo'
const { getNumber } = jest.requireActual('./demo')
test('fetchData 测试', () => {
    return fetData().then(data => {
        expect(eval(data)).toEqual('123')
    })
})
test('getNumber 测试', () => {
    expect(getNumber()).toEqual(123)
})
上一篇 下一篇

猜你喜欢

热点阅读