gpt4 book ai didi

jestjs - 手动模拟未被拾取

转载 作者:行者123 更新时间:2023-12-04 16:04:05 27 4
gpt4 key购买 nike

Jest 不提供我的手动模拟。一切似乎都在正确的目录中。我错过了什么?

src/adapters/__mocks__/Foo.js

const spy = jest.genMockFromModule('../Foo')

function doStuff() {
return { source: 'mock' }
}

spy.doStuff = doStuff
module.exports = spy

src/adapters/Foo.js

class Foo {
doStuff() {
return { source: 'real' }
}
}

module.exports = Foo

src/adapters/__tests__/Foo.js

const Foo = require('../Foo')

test('Foo', () => {
const foo = new Foo()
expect(foo.doStuff()).toEqual({ source: 'mock' })
})

测试输出:

expect(received).toEqual(expected)

Expected value to equal:
{"source": "mock"}
Received:
{"source": "real"}

Difference:

- Expected
+ Received

Object {
- "source": "mock",
+ "source": "real",
}

3 | test('Foo', () => {
4 | const foo = new Foo()
> 5 | expect(foo.doStuff()).toEqual({ source: 'mock' })
6 | })
7 |

at Object.<anonymous>.test (adapters/__tests__/Foo.js:5:25)

Jest 版本:“jest-cli”:“^23.0.0-alpha.0”

从长远来看,尝试了这个,但没有奏效。没有找到模拟,只是给了我 undefined 正如我在调用 doStuff() 时所期望的那样

src/adapters/__tests__/Foo.js

//TREID this but didn't work
jest.mock('../Foo')

const Foo = require('../Foo')

test('Foo', () => {
const foo = new Foo()
expect(foo.doStuff()).toEqual({ source: 'mock' })
})

最佳答案

试试下面的代码,这里的问题是我们模拟 ES6 类的方式,基本上,有 4 种方法可以模拟 class,如文档中所述

https://facebook.github.io/jest/docs/en/es6-class-mocks.html

src/adapters/__mocks__/Foo.js

const mock = jest.fn().mockImplementation(()=>{
return {
doStuff: jest.fn(()=>({source: 'mock'}))
}
});

module.exports = mock;

src/adapters/__tests__/Foo.js

jest.mock('../Foo');

const Foo = require('../Foo');

test('Foo', () => {
const foo = new Foo();
expect(foo.doStuff()).toEqual({ source: 'mock' })
});

(或)

内联模拟也可以工作

src/adapters/__tests__/Foo.js

jest.mock('../Foo', () => {
return jest.fn().mockImplementation(() => {
return {
doStuff: jest.fn(() => ({ source: 'mock' }))
}
});
});


const Foo = require('../Foo');

test('Foo', () => {
const foo = new Foo();
expect(foo.doStuff()).toEqual({ source: 'mock' })
});

关于jestjs - 手动模拟未被拾取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482257/

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