开玩笑的嘲笑班力不同,打字稿

时间:2019-05-23 14:28:02

标签: javascript typescript unit-testing jestjs

这又是我,举一个非常简单的例子。 在简历中,我需要对模拟类做出不同的响应。

这是我返回对象的简单类

from dask import compute, delayed
import pandas as pd
from sklearn.metrics import mean_squared_error as mse
filenames = [...]

def compute_mse(file_name):
    df = pd.read_csv(file_name)
    prediction = df['Close'][:-1]
    observed = df['Close'][1:]
    return mse(observed, prediction)

delayed_results = [delayed(compute_mse)(file_name) for file_name in filenames]
mean_squared_errors = compute(*delayed_results, scheduler="processes")

这是 class Producer { hello() { return { message:'Class: Hello', } } } export default Producer; 文件夹中的模拟类

__mocks__

这是我的测试文件,符合我的预期

            class Producer {
                hello() {
                    return {
                        message:'__mocks__: hello',
                    }
                }
            }
            export default Producer;

我的问题是,对于其他测试,我需要与模拟文件 import Consumer from './Consumer'; jest.mock('./Producer'); test('simple test 1', () => { let consumer = new Consumer(); consumer.call(); expect(consumer.response.message).toEqual('__mocks__: hello') console.log(consumer.response) // prints on console { message: '__mocks__: hello' } });

不同的响应
Producer

2 个答案:

答案 0 :(得分:1)

对于这样的事情,__mocks__/Producer.js上创建手动模拟会更容易。

相反,使用jest.mock('./Producer');自动模拟模块...

...然后根据需要模拟Producer.prototype.hello的返回值:

import Consumer from './Consumer';

import Producer from './Producer';
jest.mock('./Producer');  // <= auto-mock Producer

test('simple test 1', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'mocked: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('mocked: hello')  // Success!
});

test('simple test 2', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'UPDATED: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('UPDATED: hello')  // Success!
});

答案 1 :(得分:0)

好吧,经过一番重新搜索后,我解决了这个问题。

        class Producer {
            hello() {
                return {
                    message:' Class: Hello ',
                }
            }
        }
        export default Producer;

模拟Producer,不需要创建 mock 文件

        import Consumer from './Consumer';
        jest.mock('./Producer');

        test('simple test 1', () => {
            // mocking Producer.hello()
            Producer.mockImplementation(() => {
                return {
                    hello: () => {
                        return {
                            message: "ths is mocked "
                        }
                    },
                };
            });  

            let consumer = new Consumer();
            consumer.call(); /// Consume.call() uses inside Producer.hello() mocked
        })