jeudi 24 août 2017

Test React component method is calling function pass as a prop

I want to test that when calling a method from a React component it trigger a function pass to the component as a props. The method is something like this:

customMethod() {
  // Do something

  this.props.trackEvent({
    category: 'eventCategory',
    action: 'eventAction',
    label: 'eventAction',
  });

  // Do something else
}

The method can be called from different ways, so I want just to make a generic test: if customMethod is called, should trigger this.props.trackEvent with data.

Is there a way to trigger a method call using jest and/or enzyme? I've read about doing something like this:

const wrapper = shallow(<AdPage {...baseProps} />);
wrapper.instance().customMethod();

But it is not working… any ideas. I'm pretty new in the testing, so maybe should I use a different approach to this kind of tests?

Testing file import

I am trying to test my file imports for files with a .xlsx extension. I have the creation of the imported table working but I can't get the assertions to work.

Here is my current test:

class testImport(TestCase):
    def setUp(self):
        self.client = Client()

    @classmethod
    def setUpTestData(cls):
        user = get_user_model().objects.create(username='xlsx_importer')
        table_name = "Test Import"
        version_name = "Master"
        publish = False
        cls.user = user
        cls.table_name = table_name
        cls.version_name = version_name
        cls.publish = publish

    def test_xlsx_import(self):
        tmp = tempfile.NamedTemporaryFile(suffix='.xlsx')
        workbook = xlsxwriter.Workbook(tmp)
        worksheet = workbook.add_worksheet()
        worksheet.set_column('A:A', 20)
        worksheet.write('A1', 'Hello')
        worksheet.write('A2', '1')
        worksheet.write('B1', 'World')
        worksheet.write('B2', '2')
        tmp.seek(0)
        workbook.close()

        table = s.create_table_from_file(
            file=tmp,
            table_name=self.table_name,
            version_name=self.version_name,
            publish=self.publish,
            created_by=self.user,
        )

What I want to do is go through the columns attached to that table (through the ORM) and make a data structure that maps from friendly name to id (and therefore dictionary key).

I can currently get:

<QuerySet [{'name': 'World', 'content_type_id': 49, 'id': 44, 'order': 1, 'commit_id': 14}, {'name': 'Hello', 'content_type_id': 49, 'id': 43, 'order': 0, 'commit_id': 14}]>

By using

table.commit_set.all()[0].column_set.all().values()

The Queryset I am testing against is:

<QuerySet [{'id': 1, '43': '1', '44': '2'}]>

where '43' equates to Hello and '44' equates to World from the first Queryset.

The assertion I want to make is to see if the values '1' and '2' are present, so as I mentioned before I need to use that first Queryset to map the friendly name (i.e. name) to the id.

Any help with this would be much appreciated.

Thanks for your time.

Espresso AppNotIdleException on Spinner (Error performing 'single click - At Coordinates: X, X and precision: X, X on view)

I have a layout with a Spinner and I am trying to select a value from it in an Espresso test. However I receive the following Exception:

Caused by: android.support.test.espresso.AppNotIdleException: Looped for 24542 iterations over 60 SECONDS. The following Idle Conditions failed .

I have searched online and it appears this can happen when the app is not idle due to another process or animation, which is possible since I hide a progress bar (set its visibility to GONE) before rendering the layout.

However, the really strange part is I have a similar test that does not fail. The only thing I can think of is the test that DOES fail, the Spinner dropdown takes up most of the width of the screen, whereas the one that passes doesn't. I have tried all sorts of ways to click on the Spinner and I cannot get it to work.

This is how I am selecting the value in the Spinner, but it fails on the first line in this one test:

    onView(allOf(withId(spinnerId), withParent(withId(parentRowLayoutId)))).perform(click());
    onView(allOf(withId(dropdownListItemLayoutId), isDisplayed(), hasDescendant(withText(textToClick)))).perform(click());

I can confirm the dropdown is displayed when the first line of code above is executed in the emulator, but it just hangs and doesn't proceed to the next line of code. All animations are turned off on the emulator. Any ideas what I am doing wrong?

Tensorflow / CNN / test one image

I have a simple request but the result seems complicated to reach.

I have done a simple model in Tensorflow based on images divided in 3 labels (quite simple).

After data importation, the model is trained + tested up to 60% of good results.

Then, I'd like to test a single image using the existing model and see if the model guesses the correct label.

The whole process is quite simple up to the test process:

#%%
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

test_image = mpimg.imread(os.path.join("images","cnn","cnn_test.png"))[:, :, :channels]
plt.imshow(test_image)
plt.axis("off")
plt.show()


X_test = test_image.reshape(-1,height, width, channels)

# initialize the variables
#sess.run(tf.global_variables_initializer())

X_test = test_image.reshape(-1, height, width, channels)

tf.reset_default_graph()


# x is the input array, which will contain the data from an image 

saver = tf.train.import_meta_graph('./02_CNN/data/my_model8.ckpt.meta')

print('meta graph imported')


X_test = test_image.reshape(-1, height, width, channels)

sess = tf.Session()
saver.restore(sess, './02_CNN/data/my_model8.ckpt')
print('model graph restored')

feed_dict = {x: X_test}

prediction = sess.run(feed_dict)


max_index = np.argmax(prediction)

print(max_index)

I have the following result:

TypeError: Fetch argument array([[[[ 0.03137255,  0.20392157,  0.36862746],
         [ 0.02745098,  0.20784314,  0.37254903],
         [ 0.02352941,  0.21176471,  0.3764706 ],
         ..., 
      ....
         [ 0.08627451,  0.08235294,  0.09019608],
         [ 0.12941177,  0.12156863,  0.12941177],
         [ 0.13725491,  0.1254902 ,  0.13725491]]]], dtype=float32) 
has invalid type <class 'numpy.ndarray'>, must be a string or Tensor. 
(Can not convert a ndarray into a Tensor or Operation.)

Any idea about how to solve this issue?

Many thanks in advance,

Nicolas

Mocha testing stubbed ajax call with a .then

I've got a jquery ajax call that looks something like this:

$.ajax({
  type: "GET",
  dataType: 'json',
  data: data,
  url: url
}).then((data, successFlag, xhr) => {
  this.props.someFunc(data)
})

In my test file, I have the jquery ajax call stubbed out with sinon and it returns a resolved promise with data:

sinon.stub($, 'ajax')
  .returns(Promise.resolve({ data: 'test data' }))

And I'm also spying on my someFunc(data) function. In my test, I'm calling a function that makes the ajax call, and then expecting my someFunc(data) to be called. However, the expectation fails, but when I put a console log in my someFunc(data) function, I can see that it is clearly being called:

component.instance().makeAjaxCall()
expect($.ajax.calledOnce).to.be.true // passes
expect(someFuncSpy.calledOnce).to.be.true // fails

Now I assume that it's failing because it's checking the expectation before then .then executes and I tried looking up some solutions dealing with testing with promises but nothing I've tried works so far (or I'm implementing it wrong). How can make sure that the .then finishes executing before I check the expectation?

Selenium nosuchelement when testing, but works in standard code

So I'm currently trying to write some tests for a webpage in a Page Object Model format. I have a separate file for my module as shown below.

var webdriver = require('selenium-webdriver'); 
var by = webdriver.By;

var driver = new webdriver.Builder() 
     .forBrowser('phantomjs')
     .build(); 

driver.get("my-url.com");

module.exports =  {
    id : function(callback){
        callback = (typeof callback === 'function') ? callback : function() {};
        driver.findElements(by.id("id")).then(function(element){
            console.log("first in here");   
            driver.findElement(by.id("id")).then(function(element){
                console.log("now in here");
                callback(element);
            });
        }); 
    } 
} 

This works fine as a piece standard node code such as

driver.get("my-url.com");
 element.id(function(el){
    el.getText().then(function(text){
       console.log(text)
});

However, as soon as I put this snippit inside a mocha test suite, it suddenly breaks with a "nosuchelement" error.

test.it('Text', function(){
    element.id(function(el){
        el.getText().then(function(text){
            console.log("Second function: " + text);
        });
    });
})

I've tried putting in time delays, but what I don't understand is that it makes it through the findElements line as it prints out the first line, however, it doens't get any further.

Should I write at least one "expect condition" in a test case?

This question could seem silly but I found no convention about it so I want to be sure.

I have a test suite that contains some tests. In one test case, I am testing something that does not return anything on success and throws an exception on error.

My question is : should I write at least one "expect-like" condition in the test ?

For example, in javascript jasmine :

describe("Test suite", () => {
  it("should pass without error", () => {
    object.doSomething(); // Throws an Error on error
    // No expect() here because I have nothing to check
  });
});