如何窥探类构造函数jest?

时间:2018-01-12 03:48:31

标签: javascript unit-testing jestjs

export class Foo {
    public static bar() {
        doSomething();
    }

    constructor(paramA, paramB) {

    } 
}

对于类中的方法,我们可以使用 jest.spyOn(Foo, 'bar')监视方法。构造函数怎么样?我们如何监视对象的实例化方式?

6 个答案:

答案 0 :(得分:3)

如果你真的想窥探构造函数,你可以这样做:

// MyClass.js

export class MyClass {
  constructor() {
    console.log("constructing");
  }
}

// MyClass.test.js

import * as MyClassModule from './MyClass';

const MyClass = MyClassModule.MyClass;

test('the constructor is called', () => {
  const constructorSpy = jest.spyOn(MyClassModule, 'MyClass');
  new MyClass();
  expect(constructorSpy).toHaveBeenCalledTimes(1);
});

答案 1 :(得分:2)

我认为没有官方方式。这就是我亲自做的事情:

expect(spy).toHaveBeenCalledWith('firstArg', 'secondArg')

然后我可以检查一下间谍:

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "NewPersonManager";

// New Person table name
private static final String TABLE_NEW_PERSON = "newPerson";

// New Person Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_ID = "id";
private static final String KEY_FACEBOOK_ID = "facebook_id";
private static final String KEY_TWITTER_ID = "twitter_id";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_NEW_PERSON_TABLE = "CREATE TABLE " + TABLE_NEW_PERSON +
            "("+KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_NAME + " TEXT, "  + KEY_FACEBOOK_ID + " TEXT," + KEY_TWITTER_ID + " TEXT " + ")";
    db.execSQL(CREATE_NEW_PERSON_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEW_PERSON);

    // Create tables again
    onCreate(db);
}
// Adding new contact
public void addNewPerson(New_Person_data newPerson) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, newPerson.getmUserName()); // Person Name
    values.put(KEY_FACEBOOK_ID, newPerson.getmFacebookId()); // Person Facebook ID
    values.put(KEY_TWITTER_ID, newPerson.getmTwitterId()); //Person Twitter ID
    // Inserting Row
    db.insert(TABLE_NEW_PERSON, null, values);
    db.close(); // Closing database connection

}

// Getting single Person
public New_Person_data getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NEW_PERSON, new String[] {KEY_ID,KEY_NAME, KEY_FACEBOOK_ID,
                    KEY_TWITTER_ID }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    New_Person_data newPerson = new New_Person_data
            ( Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
    // return New Person
    return newPerson;
}

// Getting All Persons
    public List<New_Person_data> getAllPeople() {
        List<New_Person_data> PeopleList = new ArrayList<New_Person_data>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NEW_PERSON;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                New_Person_data newPerson = new New_Person_data();
                newPerson.setID(Integer.parseInt(cursor.getString(0)));
                newPerson.setmUserName(cursor.getString(1));
                newPerson.setmFacebookId(cursor.getString(2));
                newPerson.setmTwitterId(cursor.getString(2));
                // Adding person to list
                PeopleList.add(newPerson);
            } while (cursor.moveToNext());
        }

        // return people list
        return PeopleList;
}



// Getting PEOPLE Count
public int getPeopleCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NEW_PERSON;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();

答案 2 :(得分:2)

实际上有一种方法:)
甚至在官方文档中:https://jestjs.io/docs/en/es6-class-mocks#complete-example

使用代码的方法如下:

// Foo.js
export class Foo {
    public static bar() {
        doSomething();
    }

    constructor(paramA, paramB) {

    } 
}

// Foo.spec.js
import Foo from './Foo.js';

it('test something...', () => {
    // Assuming we did something that called our constructor
    expect(Foo).toHaveBeenCalledTimes(1);
});

答案 3 :(得分:1)

很遗憾,您不能直接监视承包商。问题出在新的运算符上,它是一种语言功能,因此很难出于测试目的而分离。

要进行测试,您应该这样做:

export class Foo {
    public static bar() {
        new Foo();
    }

    constructor(paramA, paramB) {

    } 
}

然后:

jest.spyOn(Foo, 'bar').something(() => ());

答案 4 :(得分:1)

// Actual Implementation 
import { ModuleToMock} from 'module-to-mock'

const test = new ModuleToMock('value1', 'value2')

test.setUser({ name: 'test', address: 'myTest' })

// test case using jest 
 import { ModuleToMock} from 'module-to-mock'
 jest.mock('module-to-mock')

// constructor response 
   const mockedModuleResponse = {
   setUser: jest.fn(), 
   }

ModuleToMock.mockImplementation(() => mockedModuleResponse)

来自How to Use Jest to Mock Constructors

的引用

答案 5 :(得分:0)

@gillyb是对的,只是忘记了“模拟” Foo模块

// Foo.js
export class Foo {
    public static bar() {
        doSomething();
    }

    constructor(paramA, paramB) {

    } 
}

// Foo.spec.js
import Foo from './Foo.js';
jest.mock('./Foo.js');

it('test something...', () => {
    // Assuming we did something that called our constructor
    expect(Foo).toHaveBeenCalledTimes(1);
});